leetcode 273

问题

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

Example 1:

1
2
Input: 123
Output: "One Hundred Twenty Three"

Example 2:

1
2
Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

1
2
Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Example 4:

1
2
Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

分析

根据数字范围,最大的数字是 4'294'967'295,然后根据每三位为一组进行解析即可。

代码

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
class Solution {
public:
const string ones[10] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
const string tenplus[10] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
const string tens[10] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
const string hundreds = "Hundred";
const string q[4] = {"", "Thousand", "Million", "Billion"};
string numberToWordsLess100(int num) {
string ret;
int x = num/100;
int y = num%100;
if (x!=0) {
ret += ones[x] + " " + hundreds;
}
if (y == 0) return ret;
if (y < 10) {
if (ret.size() != 0) ret += " ";
ret += ones[y];
} else if (y < 20) {
if (ret.size() != 0) ret += " ";
ret += tenplus[y-10];
} else {
int k = y/10;
if (ret.size() != 0) ret += " ";
ret += tens[k];
y = y%10;
if (y != 0) {
if (ret.size() != 0) ret += " ";
ret += ones[y];
}
}
return ret;
}
string numberToWords(int num) {
if (num == 0) return "Zero";
vector<int> nums;
while (num > 0) {
nums.push_back(num%1000);
num /= 1000;
}
string ans;
for (int i = nums.size()-1; i >= 0; --i) {
if (nums[i] != 0) {
if (ans.size() != 0) ans += " ";
ans += numberToWordsLess100(nums[i]);
if (i != 0) {
ans += " " + q[i];
}
}
}
return ans;
}
};