-
Notifications
You must be signed in to change notification settings - Fork 0
/
273. Integer to English Words
43 lines (42 loc) · 1.42 KB
/
273. Integer to English Words
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
class Solution {
public String numberToWords(int num) {
if(num == 0)
return "Zero";
String[] bigString = new String[]{"Thousand","Million","Billion"};
String result = numberToWordsHelper(num%1000);
num = num/1000;
if(num > 0 && num%1000>0){
result = numberToWordsHelper(num%1000) + "Thousand " + result;
}
num = num/1000;
if(num > 0 && num%1000>0){
result = numberToWordsHelper(num%1000) + "Million " + result;
}
num = num/1000;
if(num > 0){
result = numberToWordsHelper(num%1000) + "Billion " + result;
}
return result.trim();
}
public String numberToWordsHelper(int num){
String[] digitString = new String[]{"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
String[] teenString = new String[]{"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen","Eighteen", "Nineteen"};
String[] tenString = new String[]{"","","Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
String result = "";
if(num > 99){
result += digitString[num/100] + " Hundred ";
}
num = num % 100;
if(num < 20 && num > 9){
result += teenString[num%10]+" ";
}else{
if(num > 19){
result += tenString[num/10]+" ";
}
num = num % 10;
if(num > 0)
result += digitString[num]+" ";
}
return result;
}
}