-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinteger-to-english-words.cpp
31 lines (31 loc) · 1.19 KB
/
integer-to-english-words.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
class Solution {
public:
// https://leetcode.com/problems/integer-to-english-words/discuss/70651/Fairly-Clear-4ms-C++-solution
string numberToWords(int n) {
return n ? toWords(n).substr(1) : "Zero";
}
private:
vector<string> ones = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
vector<string> tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string toWords(int n) {
if (n >= 1000000000) {
return toWords(n / 1000000000) + " Billion" + toWords(n % 1000000000);
}
if (n >= 1000000) {
return toWords(n / 1000000) + " Million" + toWords(n % 1000000);
}
if (n >= 1000) {
return toWords(n / 1000) + " Thousand" + toWords(n % 1000);
}
if (n >= 100) {
return toWords(n / 100) + " Hundred" + toWords(n % 100);
}
if (n >= 20) {
return " " + tens[n / 10] + toWords(n % 10);
}
if (n >= 1) {
return " " + ones[n];
}
return "";
}
};