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 52 53 54 55 56 57 58 59
| class Solution { private: vector<string> singles = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; vector<string> ten2Twenty = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; vector<string> tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
public: string underHundred(int n) { string ans; int hundred = n / 100; if (hundred) { ans += singles[hundred] + " Hundred "; } n %= 100; if (n < 20 && n >= 10) { ans += ten2Twenty[n % 10] + " "; return ans; } if (n >= 20) { ans += tens[n / 10] + " "; } n %= 10; if (n == 0) return ans; ans += singles[n % 10] + " "; return ans; }
string recur(int n) { string ans;
int billion = n / 1000000000; n %= 1000000000; int million = n / 1000000; n %= 1000000; int thousand = n / 1000; n %= 1000;
if (billion) { ans += recur(billion) + "Billion "; } if (million) { ans += recur(million) + "Million "; } if (thousand) { ans += recur(thousand) + "Thousand "; }
ans += underHundred(n); return ans; }
string numberToWords(int num) { if (num == 0) return "Zero"; string ans = recur(num); ans.pop_back(); return ans; } };
|