-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
36 lines (35 loc) · 1.13 KB
/
Copy pathSolution.java
File metadata and controls
36 lines (35 loc) · 1.13 KB
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 {
String[] less20 = {
"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"
};
String[] tens = {
"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
};
String[] thousands = {
"", "Thousand", "Million", "Billion"
};
public String numberToWords(int num) {
if (num == 0) return "Zero";
String res = "";
int i = 0;
while (num > 0) {
if (num % 1000 != 0) {
res = helper(num % 1000) + thousands[i] + " " + res;
}
num /= 1000;
i++;
}
return res.trim();
}
private String helper(int num) {
if (num == 0) return "";
if (num < 20) {
return less20[num] + " ";
} else if (num < 100) {
return tens[num / 10] + " " + helper(num % 10);
} else {
return less20[num / 100] + " Hundred " + helper(num % 100);
}
}
}