Skip to content

Commit f63e63d

Browse files
authored
Create 273. Integer to English Words (#549)
2 parents d7692d7 + 816b30b commit f63e63d

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

273. Integer to English Words

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Solution {
2+
public:
3+
string ones[10] = {"", "One", "Two", "Three", "Four",
4+
"Five", "Six", "Seven", "Eight", "Nine"};
5+
string teens[10] = {"", "Eleven", "Twelve", "Thirteen",
6+
"Fourteen", "Fifteen", "Sixteen", "Seventeen",
7+
"Eighteen", "Nineteen"};
8+
string tens[10] = {"", "Ten", "Twenty", "Thirty", "Forty",
9+
"Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
10+
string thousands[10] = {"", "Thousand", "Million", "Billion"};
11+
string convert_thous(int num) {
12+
string res;
13+
if (num >= 100) {
14+
res += ones[num / 100] + " Hundred ";
15+
num %= 100;
16+
}
17+
if (num >= 20) {
18+
res += tens[num / 10] + " ";
19+
num %= 10;
20+
} else if (num > 10 && num < 20) {
21+
res += teens[num - 10] + " ";
22+
num = 0;
23+
}
24+
if (num == 10)
25+
res+= "Ten";
26+
if (num > 0) {
27+
res += ones[num] + " ";
28+
}
29+
return res;
30+
}
31+
string numberToWords(int num) {
32+
ios::sync_with_stdio(false);
33+
cin.tie(0);
34+
if (num == 0)
35+
return "Zero";
36+
string result;
37+
int tho = 0;
38+
while (num > 0) {
39+
int temp = num % 1000;
40+
if (temp > 0) {
41+
result = convert_thous(temp) + thousands[tho] + " " + result;
42+
}
43+
num /= 1000;
44+
tho++;
45+
}
46+
auto it = std::find_if_not(result.rbegin(), result.rend(), ::isspace);
47+
result.erase(it.base(), result.end());
48+
return result;
49+
}
50+
};

0 commit comments

Comments
 (0)