-
Notifications
You must be signed in to change notification settings - Fork 0
/
integer-to-english-words.cc
56 lines (55 loc) · 1.48 KB
/
integer-to-english-words.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
class Solution {
public:
vector<string> dict_one = {
"Zero", "One", "Two","Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen",
};
vector<string> dict_ten = {
"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
};
vector<string> posts = { "", "Thousand", "Million", "Billion", "Trillion" };
string numberToWords(int num) {
if (num == 0) return dict_one[num];
int post_index = 0;
string postfix = posts[post_index];
string res = "";
while(num > 0) {
int remain = num % 1000;
string s = parse(remain);
if (s == "") {
res = s + res;
} else {
if (postfix == "") {
res = s;
} else {
res = s + " " + postfix + (res == "" ? res : " " + res);
}
}
num = num / 1000;
postfix = posts[++post_index];
}
return res;
}
string parse(int v) {
string res = "";
if (v / 100 > 0) {
res += (dict_one[v / 100] + " " + "Hundred");
}
v = v % 100;
if (v <= 19) {
if (v == 0) return res;
res += (res == "" ? dict_one[v] : " " + dict_one[v]);
return res;
} else {
int tens = v / 10;
res += (res == "" ? dict_ten[tens] : " " + dict_ten[tens]);
v = v % 10;
}
if (v != 0) {
res += (" " + dict_one[v]);
return res;
} else {
return res;
}
}
};