-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathIntegertoEnglishWords.java
More file actions
39 lines (37 loc) · 1.34 KB
/
IntegertoEnglishWords.java
File metadata and controls
39 lines (37 loc) · 1.34 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
37
38
39
public class Solution {
String[] belowTwenty = {"", "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 level = 0;
while (num > 0) {
int remain = num % 1000;
String str = convertToStr(remain);
if (str.length() > 0) {
str += " " + thousands[level] + " ";
}
// A lot of trim around the corner cases
res = str.trim() + " " + res.trim();
level++;
num /= 1000;
}
return res.trim();
}
public String convertToStr(int remain) {
String str = "";
if (remain >= 100) {
str += belowTwenty[remain / 100] + " Hundred ";
}
remain %= 100;
if (remain < 20) {
str += belowTwenty[remain];
} else {
str += tens[remain / 10] + " " + belowTwenty[remain % 10];
}
return str.trim();
}
}