-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path273.integer-to-english-words.cpp
More file actions
101 lines (100 loc) · 2.54 KB
/
273.integer-to-english-words.cpp
File metadata and controls
101 lines (100 loc) · 2.54 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
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
/*
* @lc app=leetcode id=273 lang=cpp
*
* [273] Integer to English Words
*
* https://leetcode.com/problems/integer-to-english-words/description/
*
* algorithms
* Hard (24.92%)
* Likes: 676
* Dislikes: 1899
* Total Accepted: 125.4K
* Total Submissions: 497.9K
* Testcase Example: '123'
*
* Convert a non-negative integer to its english words representation. Given
* input is guaranteed to be less than 2^31 - 1.
*
* Example 1:
*
*
* Input: 123
* Output: "One Hundred Twenty Three"
*
*
* Example 2:
*
*
* Input: 12345
* Output: "Twelve Thousand Three Hundred Forty Five"
*
* Example 3:
*
*
* Input: 1234567
* Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty
* Seven"
*
*
* Example 4:
*
*
* Input: 1234567891
* Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty
* Seven Thousand Eight Hundred Ninety One"
*
*
*/
// @lc code=start
class Solution {
public:
string numberToWords(int num) {
if (num == 0)
return "Zero";
digitName = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
tenthName = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
tyName = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
vector<string> segs(4, "");
int idx = 0;
while (num) {
toHundred(segs[idx], num % 1000);
num /= 1000;
++idx;
}
string result = "";
const vector<string> names{"", " Thousand", " Million", " Billion"};
bool needBlank = false;
while (idx--) {
if (!segs[idx].empty()) {
result += (needBlank ? " " : "") + segs[idx] + names[idx];
needBlank = true;
}
}
return result;
}
private:
vector<string> digitName;
vector<string> tenthName;
vector<string> tyName;
void toHundred(string &s, int num) {
string h = "", t = "", o = "";
int digits = num % 10;
if (digits)
o = digitName[digits-1];
num /= 10;
int tens = num % 10;
if (tens == 1) {
o = "";
t = tenthName[digits];
}
else if (tens)
t = tyName[tens - 2] + (digits ? " ": "");
num /= 10;
int hundreds = num;
if (hundreds)
h = digitName[hundreds-1] + " Hundred" + (digits || tens ? " " : "");
s = h + t + o;
}
};
// @lc code=end