Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
For example,
123 -> "One Hundred Twenty Three"12345 -> "Twelve Thousand Three Hundred Forty Five"1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Hint:
- Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.
- Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.
- There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)
一定要考虑各种边界情况。正如提示里所说的。
1 class Solution { 2 public: 3 string getWord(int num, string *digit, string *digit1) { 4 if (num == 0) return "Zero"; 5 string res; 6 int h = num / 100; 7 num %= 100; 8 if (h > 0) res += digit[h] + " Hundred"; 9 if (num == 0) return res;10 else if (h > 0) res += " ";11 if (num < 20) {12 res += digit[num];13 } else {14 h = num / 10;15 num %= 10;16 res += digit1[h];17 if (num != 0) res += " " + digit[num];18 }19 return res;20 }21 string numberToWords(int num) {22 if (num == 0) return "Zero";23 string digit[20] = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",24 "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"25 };26 string digit1[10] = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};27 string digit2[10] = { "", "Thousand", "Million", "Billion"};28 vectorwords;29 string str;30 int num2, cnt = 0;31 while (num != 0) {32 num2 = num % 1000;33 str = getWord(num2, digit, digit1);34 if (str != "Zero") {35 if (cnt > 0) words.push_back(str + " " + digit2[cnt]);36 else words.push_back(str);37 }38 num /= 1000;39 ++cnt;40 }41 string res;42 for (int i = (int)words.size() - 1; i > 0; --i) {43 res += words[i] + " ";44 }45 res += words.front();46 return res;47 }48 };