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
| unordered_map<int, string> m = { {1e9, "Billion"}, {1e6, "Million"}, {1e3, "Thousand"}, {100, "Hundred"}, {90, "Ninety"}, {80, "Eighty"}, {70, "Seventy"}, {60, "Sixty"}, {50, "Fifty"}, {40, "Forty"}, {30, "Thirty"}, {20, "Twenty"}, {19, "Nineteen"}, {18, "Eighteen"}, {17, "Seventeen"}, {16, "Sixteen"}, {15, "Fifteen"}, {14, "Fourteen"}, {13, "Thirteen"}, {12, "Twelve"}, {11, "Eleven"}, {10, "Ten"}, {9, "Nine"}, {8, "Eight"}, {7, "Seven"}, {6, "Six"}, {5, "Five"}, {4, "Four"}, {3, "Three"}, {2, "Two"}, {1, "One"}, {0, "Zero"} }; vector<int> v = {1000000000, 1000000, 1000, 100}; class Solution { public: string numberToWords(int num) { string res; if (auto it = lower_bound(begin(v), end(v), num, greater<>()); it != end(v)) { int x = *it; res.append(numberToWords(num / x).append(" ").append(m[x])); num %= x; return num > 0 ? res.append(" ").append(numberToWords(num)) : res; } if (num >= 20) { res.append(m[num - num % 10]); num %= 10; return num > 0 ? res.append(" ").append(numberToWords(num)) : res; } return m[num]; } };
|