For readability's sake, it may be best to just hard-code the POSTNET strings for the digits 0 through 9 (perhaps in a static variable in your ZipCode
class) and just perform a lookup for the five digits in the zip code. A minimal example is:
#include <array>
#include <iostream>
#include <string>
std::string zip_to_postnet(const std::string& zip)
{
std::array<std::string,10> lookup{"11000", "00011", "00101", "00110",
"01001", "01010", "01100", "10001",
"10010", "10100"};
std::string result = "1";
for (unsigned int i = 0; i < 5; ++i)
{
int digit = zip[i] - '0';
result += lookup[digit];
}
return result + "1";
}
int main()
{
std::cout << zip_to_postnet("24060") << std::endl;
std::cout << zip_to_postnet("92064") << std::endl;
std::cout << zip_to_postnet("11518") << std::endl;
return 0;
}
A demo passes your three test cases. (This uses C++11's std::array
, but you could use a normal array.) If you are intent on retaining your original algorithm, please say so.
EDIT: PS, since I see you are using C++11, just a quick note that it is preferable to use something like std::to_string
instead of itoa
if trying to convert an integer (e.g. a zip code) to string. (See line 3 of your question's code.)