-
Notifications
You must be signed in to change notification settings - Fork 0
/
integerToEnglish.txt
27 lines (23 loc) · 1.07 KB
/
integerToEnglish.txt
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
273. Integer to English Words
Convert a non-negative integer num to its English words representation.
class Solution {
public:
string ones[20] = {"", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine", " Ten", " Eleven", " Twelve", " Thirteen", " Fourteen", " Fifteen", " Sixteen", " Seventeen", " Eighteen", " Nineteen"};
string tens[10] = {"", " Ten", " Twenty", " Thirty", " Forty", " Fifty", " Sixty", " Seventy", " Eighty", " Ninety"};
string thousands[4] = {"", " Thousand", " Million", " Billion"};
string helper(int num){
if(num < 20) return ones[num];
if(num < 100) return tens[num/10] + helper(num % 10);
if(num < 1000) return helper(num/100) + " Hundred" + helper(num % 100);
for(int i = 3 ; i >= 0 ; i--){
if(num >= pow(1000,i)){
return helper(num/pow(1000,i))+thousands[i]+helper(num%(int)pow(1000,i));
}
}
return "";
}
string numberToWords(int num) {
if(num == 0) return "Zero";
return helper(num).substr(1);
}
};