-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0273_Integer_to_English_Words.cpp
More file actions
56 lines (51 loc) · 2.68 KB
/
0273_Integer_to_English_Words.cpp
File metadata and controls
56 lines (51 loc) · 2.68 KB
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
// ███████╗ █████╗ ███╗ ██╗ ██████╗ █████╗ ██████╗ ██████╗ ██╗ ██╗
// ██╔════╝ ██╔══██╗ ████╗ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║ ██║
// ███████╗ ███████║ ██╔██╗ ██║ ██║ ██║ ███████║ ██████╔╝ ██████╔╝ ███████║
// ╚════██║ ██╔══██║ ██║╚██╗██║ ██║ ██║ ██╔══██║ ██╔═██╗ ██╔══██╗ ██╔══██║
// ███████║ ██║ ██║ ██║ ╚████║ ██████╔╝ ██║ ██║ ██║ ██╗ ██████╔╝ ██║ ██║
// ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝
#pragma GCC optimize("Ofast", "inline", "ffast-math", "unroll-loops","no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native", "f16c")
auto init = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return 'c';
}();
class Solution {
public:
string numberToWords(int num) {
if (num == 0)
return "Zero";
return helper(num);
}
private:
const vector<string> belowTwenty{
"", "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
"Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
const vector<string> tens{"", "", "Twenty", "Thirty", "Forty",
"Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string helper(int num) {
string s;
if (num < 20)
s = belowTwenty.at(num);
else if (num < 100)
s = tens.at(num / 10) + " " + belowTwenty.at(num % 10);
else if (num < 1000)
s = helper(num / 100) + " Hundred " + helper(num % 100);
else if (num < 1000000)
s = helper(num / 1000) + " Thousand " + helper(num % 1000);
else if (num < 1000000000)
s = helper(num / 1000000) + " Million " + helper(num % 1000000);
else
s = helper(num / 1000000000) + " Billion " + helper(num % 1000000000);
trim(s);
return s;
}
void trim(string& s) {
s.erase(0, s.find_first_not_of(' '));
s.erase(s.find_last_not_of(' ') + 1);
}
};