-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_16.08_numberToWords.cc
72 lines (68 loc) · 1.66 KB
/
Problem_16.08_numberToWords.cc
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
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <string>
#include <vector>
using namespace std;
class Solution
{
private:
vector<string> singles = {"", "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine"};
vector<string> teens = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
"Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
vector<string> tens = {"", "Ten", "Twenty", "Thirty", "Forty",
"Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
vector<string> thousands = {"", "Thousand", "Million", "Billion"};
public:
string numberToWords(int num)
{
if (num == 0)
{
// 直接返回 0
return "Zero";
}
string ans;
// 从高位到低位分 4 组,每组单位依次是 10^9, 10^6, 10^3, 1
// 除了最低组外,每一组都有对应的单词,分别是 "Billion","Million","Thousand"
for (int i = 3, unit = 1e9; i >= 0; i--, unit /= 1e3)
{
int curNum = num / unit;
if (curNum != 0)
{
num -= curNum * unit;
string cur;
f(cur, curNum);
cur += thousands[i] + " ";
ans += cur;
}
}
while (ans.back() == ' ')
{
ans.pop_back();
}
return ans;
}
void f(string& cur, int num)
{
if (num == 0)
{
return;
}
else if (num < 10)
{
cur += singles[num] + " ";
}
else if (num < 20)
{
cur += teens[num - 10] + " ";
}
else if (num < 100)
{
cur += tens[num / 10] + " ";
f(cur, num % 10);
}
else
{
cur += singles[num / 100] + " Hundred ";
f(cur, num % 100);
}
}
};