Integer to English Words LeetCode solution in C++

1
unordered_map<int, string> mp_0 = {
2
{1, "One "}, {2, "Two "}, {3, "Three "}, {4, "Four "}, {5, "Five "},
3
{6, "Six "}, {7, "Seven "}, {8, "Eight "}, {9, "Nine "}, {10, "Ten "},
4
{11, "Eleven "}, {12, "Twelve "}, {13, "Thirteen "}, {14, "Fourteen "}, {15, "Fifteen "},
5
{16, "Sixteen "}, {17, "Seventeen "}, {18, "Eighteen "}, {19, "Nineteen "}};
6

7
unordered_map<int, string> mp_10 = {{20, "Twenty "}, {30, "Thirty "}, {40, "Forty "},
8
{50, "Fifty "}, {60, "Sixty "}, {70, "Seventy "},
9
{80, "Eighty "}, {90, "Ninety "}};
10

11
class Solution {
12
void Solve2(string &ans, int num) {
13
ans = mp_0[num] + ans;
14
}
15

16
void Solve(string &ans, int num) {
17
int factor = 1;
18
for (int i = 0; num > 0; i++) {
19
if (factor == 1) {
20
if (num % 100 < 20) {
21
Solve2(ans, num % 100);
22
factor = factor * 10;
23
num = num / 10;
24
} else {
25
if (num % 10 != 0) ans = mp_0[num % 10] + ans;
26
}
27
}
28

29
else if (factor == 10) {
30
if (num % 10 != 0) ans = mp_10[(num % 10) * 10] + ans;
31
}
32

33
else if (factor == 100) {
34
if (num % 10 != 0) ans = (mp_0[num % 10] + "Hundred ") + ans;
35
}
36

37
factor = factor * 10;
38
num = num / 10;
39
}
40
}
41

42
public:
43
string numberToWords(int num) {
44
// 2,147,483,647
45

46
if (num == 0) return "Zero";
47

48
string ans;
49

50
for (int i = 0; num > 0; i++) {
51
if (i == 1) {
52
if (num % 1000 > 0) ans = "Thousand " + ans;
53
} else if (i == 2) {
54
if (num % 1000 > 0) ans = "Million " + ans;
55
} else if (i == 3)
56
ans = "Billion " + ans;
57

58
Solve(ans, num % 1000);
59
num = num / 1000;
60
}
61
ans.pop_back();
62
return ans;
63
}
64
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0