This problem is not difficult. But it is not easy to have a bug-free code. As you write your codes according to the hints, the most important thing is to handle all the edge cases without making the code ugly :-) Well, the key to simplify the code is to us hard coding. This link provides a nice solution, whose Java code is rewritten below in C++. Since C++ has no convenient functions like trim
and I do not want to create one on my own, I handle the " "
and ' '
carefully using some tricks from this link (for example, I include the space in the words of the numbers).
1 class Solution { 2 public: 3 string numberToWords(int num) { 4 vector<string> bigs = { "", " Thousand", " Million", " Billion" }; 5 int i = 0; 6 string ans; 7 while (num) { 8 if (num % 1000) ans = numberWords(num % 1000) + bigs[i] + ans; 9 i++, num /= 1000; 10 } 11 return ans.length() ? ans.substr(1) : "Zero"; 12 } 13 private: 14 string numberWords(int num) { 15 char* one[] = { "", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine" }; 16 char* ones[] = { " Ten", " Eleven", " Twelve", " Thirteen", " Fourteen", " Fifteen", " Sixteen", " Seventeen", " Eighteen", " Nineteen" }; 17 char* tens[] = { "", "", " Twenty", " Thirty", " Forty", " Fifty", " Sixty", " Seventy", " Eighty", " Ninety" }; 18 string ans; 19 if (num > 99) ans += string(one[num / 100]) + " Hundred"; 20 num %= 100; 21 if (num > 9 && num < 20) ans += ones[num % 10]; 22 else { 23 if (num > 19) ans += tens[num / 10]; 24 num %= 10; 25 if (num) ans += one[num]; 26 } 27 return ans; 28 } 29 };