-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path200621-2.cpp
72 lines (70 loc) · 1.99 KB
/
200621-2.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
// https://leetcode-cn.com/problems/integer-to-english-words/
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string numberToWords(int num) {
static const char* WORDS[] = {
"Zero", "One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten",
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen",
"Sixteen", "Seventeen", "Eighteen", "Nineteen"
};
static const char* WORDS2[] = {
"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
};
string s;
if (num < 20) {
s = WORDS[num];
} else if (num < 100) {
s = WORDS2[num / 10 - 2];
if (num % 10 > 0) {
s += " " + numberToWords(num % 10);
}
} else if (num < 1000) {
s = WORDS[num / 100];
s += " Hundred";
if (num % 100 > 0) {
s += " ";
s += numberToWords(num % 100);
}
} else if (num < 1000000) {
s = numberToWords(num / 1000);
s += " Thousand";
if (num % 1000 > 0) {
s += " ";
s += numberToWords(num % 1000);
}
} else if (num < 1000000000) {
s = numberToWords(num / 1000000);
s += " Million";
if (num % 1000000 > 0) {
s += " ";
s += numberToWords(num % 1000000);
}
} else {
s = numberToWords(num / 1000000000);
s += " Billion";
if (num % 1000000000 > 0) {
s += " ";
s += numberToWords(num % 1000000000);
}
}
return s;
}
};
int main()
{
Solution s;
for (int i = 0; i <= 21; ++i) {
cout << s.numberToWords(i) << endl;
}
cout << s.numberToWords(123) << endl; // answer: "One Hundred Twenty Three"
cout << s.numberToWords(12345) << endl; // answer: "Twelve Thousand Three Hundred Forty Five"
cout << s.numberToWords(1234567) << endl; // answer: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
cout << s.numberToWords(1234567891) << endl; // answer: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
cout << s.numberToWords(101) << endl;
cout << s.numberToWords(3055000) << endl;
return 0;
}