-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathmain.cpp
124 lines (119 loc) · 2.33 KB
/
main.cpp
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <cstdlib>
#include <iostream>
#include <map>
#include <queue>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution {
private:
const vector<string> words = {
"Zero",
"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",
};
const int BILLION = 1000000000;
const int MILLION = 1000000;
const int THOUSAND = 1000;
string getThreeDigitWord(int n) {
string result = "";
if (n >= 100) {
result += words[n / 100];
result += " Hundred";
n %= 100;
}
if (n >= 20) {
if (result.size() > 0) {
result += " ";
}
result += tens[n / 10];
if (n % 10 > 0) {
result += " ";
result += words[n % 10];
}
} else if (n > 0) {
if (result.size() > 0) {
result += " ";
}
result += words[n];
}
return result;
}
public:
string numberToWords(int num) {
string result = "";
if (num == 0) {
return words[0];
}
if (num >= BILLION) {
result += getThreeDigitWord(num / BILLION);
result += " Billion";
num %= BILLION;
}
if (num >= MILLION) {
if (result.size() > 0) {
result += " ";
}
result += getThreeDigitWord(num / MILLION);
result += " Million";
num %= MILLION;
}
if (num >= THOUSAND) {
if (result.size() > 0) {
result += " ";
}
result += getThreeDigitWord(num / THOUSAND);
result += " Thousand";
num %= THOUSAND;
}
if (num > 0) {
if (result.size() > 0) {
result += " ";
}
result += getThreeDigitWord(num);
}
return result;
}
};
int main() {
Solution sol;
cout << sol.numberToWords(0) << endl;
cout << sol.numberToWords(20) << endl;
cout << sol.numberToWords(100) << endl;
cout << sol.numberToWords(123) << endl;
cout << sol.numberToWords(12345) << endl;
cout << sol.numberToWords(1234567) << endl;
return 0;
}