I am writing a program that is supposed to take a ZIP code (represented by an int
) and parse it into its POSTNET equivalent (represented by a C++ std::string
) and vice versa. The algorithm to convert a POSTNET code into a ZIP code works fine, but the algorithm to convert a ZIP code into POSTNET does not work right. I have isolated the cause of the problem to be the getSequence()
function; is there any problem there?
Here's my code:
string ZipCode::getBarCode()
{
string zipCode = itoa(this->zipCode, new char[5], 10);
string sequences[5];
for(int i = 0; i < 5; ++i)
sequences[i] = getSequence(zipCode[i] - '0');
string toReturn = "1";
for(string &sequence : sequences)
toReturn += sequence;
return toReturn + "1";
}
string ZipCode::getSequence(int digit)
{
if(digit == 0)
return "11000";
string toReturn = "00000";
int values[4] = {7, 4, 2, 1};
for(int i = 0; i < 4; ++i)
if(digit < values[i])
{
toReturn = toReturn.replace(i, 1, "1");
digit -= values[i];
}
if(containsOnlyOne1(toReturn))
toReturn = toReturn.replace(4, 1, "1");
return toReturn;
}
bool ZipCode::containsOnlyOne1(std::string str)
{
int instancesOfOne = 0;
for(int i = 0; i < str.length(); ++i)
if(str[i] == '1')
instancesOfOne++;
return instancesOfOne == 1;
}
Additionally, here are some test cases:
ZIP Code Expected Output Actual Output
24060 100101010011100001100110001 111110111101100011110110001
92064 110100001011100001100010011 100000111101100011110111101
11518 100011000110101000011100101 111110111101111011110000001
Not sure if this helps, but I am a Java programmer learning C++ for the first time.
I think your problem is here:
if(digit < values[i])
That should be >=
not <
.
The biggest hint is what comes next - you subtract values[i]
from digit
, which will result in a negative number if the <
condition is true. That doesn't seem at all like what you want.