-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC.JAVA
38 lines (32 loc) · 1.53 KB
/
LC.JAVA
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
class Solution {
private static final String[] belowTen = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
private static final String[] belowTwenty = { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
private static final String[] belowHundred = { "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
public String numberToWords(int num) {
if (num == 0) {
return "Zero";
}
return convertToWords(num);
}
private String convertToWords(int num) {
if (num < 10) {
return belowTen[num];
}
if (num < 20) {
return belowTwenty[num - 10];
}
if (num < 100) {
return belowHundred[num / 10] + (num % 10 != 0 ? " " + convertToWords(num % 10) : "");
}
if (num < 1000) {
return convertToWords(num / 100) + " Hundred" + (num % 100 != 0 ? " " + convertToWords(num % 100) : "");
}
if (num < 1000000) {
return convertToWords(num / 1000) + " Thousand" + (num % 1000 != 0 ? " " + convertToWords(num % 1000) : "");
}
if (num < 1000000000) {
return convertToWords(num / 1000000) + " Million" + (num % 1000000 != 0 ? " " + convertToWords(num % 1000000) : "");
}
return convertToWords(num / 1000000000) + " Billion" + (num % 1000000000 != 0 ? " " + convertToWords(num % 1000000000) : "");
}
}