1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| class Solution { public: string numberToWords(int num) { int splited[4] = { 0 }; string numbers[] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; string tensnumbers[] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; string biggertennumbers[] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; if (num == 0) { return "Zero"; } for (int i = 0; i < 4; i++) { splited[i] = num % 1000; num = num / 1000; } string ans = ""; for (int i = 3; i >= 0; i--) { int data = splited[i]; if (data > 0) { if (data / 100) { ans += numbers[data / 100] + " Hundred "; } data = data % 100; if (data > 0) { if (data < 10) { ans += numbers[data] + " "; } else if (data >= 20) { ans += tensnumbers[data / 10] + " "; data = data % 10; if (data > 0) { ans += numbers[data] + " "; } } else { ans += biggertennumbers[data - 10] + " "; } } if (i == 3) { ans += "Billion "; } else if (i == 2) { ans += "Million "; } else if (i == 1) { ans += "Thousand "; } } } return ans.substr(0, ans.size() - 1); } };
|