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
73
74
75
76
77
78
79
80
81
82
| class Solution {
public:
string numberToWords(int num) {
if (num == 0) {
return "Zero";
}
string result;
int index = 0;
while (num > 0) {
int current = num % 1000;
if (current != 0) {
string part = convert_to_words(current);
if (!units[index].empty()) {
part += " " + units[index];
}
if (!result.empty()) {
part += " ";
}
result = part + result;
}
++index;
num /= 1000;
}
return result;
}
private:
const array<string, 10>
ones{"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
const array<string, 10> teens{
"Ten",
"Eleven",
"Twelve",
"Thirteen",
"Fourteen",
"Fifteen",
"Sixteen",
"Seventeen",
"Eighteen",
"Nineteen"};
const array<string, 10>
tens{"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
const array<string, 4> units{"", "Thousand", "Million", "Billion"};
string convert_to_words(int num) {
string result;
if (num >= 100) {
result += ones[num / 100] + " Hundred";
num %= 100;
if (num > 0) {
result += " ";
}
}
if (num >= 20) {
result += tens[num / 10];
if (num % 10 > 0) {
result += " " + ones[num % 10];
}
} else if (num >= 10) {
result += teens[num - 10];
} else if (num > 0) {
result += ones[num];
}
return result;
}
};
|