273. Integer to English Words

273. Integer to English Words

Description

Convert a non-negative integer num to its English words representation.

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

  • 0 <= num <= 2^31 - 1

Hints/Notes

Solution

Language: C++

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
class Solution {
public:
vector<string> underTwenty = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen", "Eighteen", "Nineteen"};
vector<string> tens = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string numberToWords(int num) {
if (!num) {
return "Zero";
}
string numStr = to_string(num);
string res;
// 1,234,567,890
// 9,876,543,210
if ((numStr.size() - 1) / 3 >= 3) {
int len = numStr.size() % 3;
if (!len) len = 3;
int billion = stoi(numStr.substr(0, len));
res += within_thousand(billion) + " Billion";
numStr.erase(0, len);
}
if ((numStr.size() - 1) / 3 >= 2) {
int len = numStr.size() % 3;
if (!len) len = 3;
int million = stoi(numStr.substr(0, len));
if (million) {
if (!res.empty()) res += " ";
res += within_thousand(million) + " Million";
}
numStr.erase(0, len);
}
if ((numStr.size() - 1) / 3 >= 1) {
int len = numStr.size() % 3;
if (!len) len = 3;
int thousand = stoi(numStr.substr(0, len));
if (thousand) {
if (!res.empty()) res += " ";
res += within_thousand(thousand) + " Thousand";
}
numStr.erase(0, len);
}
int len = numStr.size() % 3;
if (!len) len = 3;
num = stoi(numStr.substr(0, len));
if (num) {
if (!res.empty()) res += " ";
res += within_thousand(num);
}
return res;
}

string within_thousand(int num) {
string res;
if (num >= 100) {
int hundred = num / 100;
num %= 100;
res += underTwenty[hundred] + " Hundred";
}
if (!num) {
return res;
}
if (!res.empty()) {
res += " ";
}
if (num >= 20) {
int ten = num / 10;
int digit = num % 10;
res += tens[ten - 2];
if (digit != 0) {
res += " " + underTwenty[digit];
}
} else {
res += underTwenty[num];
}
return res;
}
};