-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution2.java
36 lines (34 loc) · 1.2 KB
/
Solution2.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
class Solution {
private String[] lt20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen", "Eighteen", "Nineteen"};
private String[] tens
= {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
private String[] thousands = {"Billion", "Million", "Thousand", ""};
public String numberToWords(int num) {
if (num == 0) {
return "Zero";
}
StringBuilder sb = new StringBuilder();
for (int i = 1000000000, j = 0; i > 0; i /= 1000, ++j) {
if (num / i == 0) {
continue;
}
sb.append(transfer(num / i)).append(thousands[j]).append(' ');
num %= i;
}
return sb.toString().trim();
}
private String transfer(int num) {
if (num == 0) {
return "";
}
if (num < 20) {
return lt20[num] + " ";
}
if (num < 100) {
return tens[num / 10] + " " + transfer(num % 10);
}
return lt20[num / 100] + " Hundred " + transfer(num % 100);
}
}