-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path273. Integer to English Words
75 lines (62 loc) · 2.01 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
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
Hard
Topics
Companies
Hint
Convert a non-negative integer num to its English words representation.
Example 1:
Input: num = 123
Output: "One Hundred Twenty Three"
Example 2:
Input: num = 12345
Output: "Twelve Thousand Three Hundred Forty Five"
Example 3:
Input: num = 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Constraints:
0 <= num <= 231 - 1
solution:
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 && num %1000 >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;
}
}
by this we can solve