Just take care of corner cases.
vector<string> sec3 = { "", "Thousand", "Million", "Billion" }; vector<string> sig = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }; vector<string> teen = { "", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; vector<string> ty = { "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; class Solution { string sec3to(int num) { int a = num % 10; int b = (num / 10) % 10; int c = (num / 100) % 10; string ret; if (b == 1 && a != 0) // teens { ret += teen[a]; } else if (a == 0 && b != 0) // ty-s { ret += ty[b]; } else // all other { if (b > 0) ret += ty[b] + " "; if (a > 0) ret += sig[a]; } if (c > 0) { string hstr = sig[c] + " Hundred"; if (ret.empty()) ret = hstr; else ret = hstr + " " + ret; } return ret; } public: string numberToWords(int num) { if (num == 0) return "Zero"; string ret; int sec = num % 1000; int seci = 0; while (num) { string secstr = sec3to(sec); if (!secstr.empty()) ret = secstr + (seci > 0 ? (" " + sec3[seci] + (ret.empty() ? "" : " " + ret)) : ""); // num /= 1000; sec = num % 1000; seci++; } return ret; } };