-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path273.integer-to-english-words.java
More file actions
46 lines (39 loc) · 1.33 KB
/
273.integer-to-english-words.java
File metadata and controls
46 lines (39 loc) · 1.33 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
40
41
42
43
44
45
/*
* @lc app=leetcode id=273 lang=java
*
* [273] Integer to English Words
*/
// @lc code=start
class Solution {
private String[] lessThan20 = new String[]{"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private String[] tenTh = new String[]{"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
private String[] thousand = new String[]{"", "Thousand", "Million", "Billion"};
public String numberToWords(int num) {
String result = "";
if (num == 0) {
return "Zero";
}
int index = 0;
while (num > 0) {
if (num % 1000 != 0) {
result = getDigit(num % 1000) + thousand[index] + " " + result;
}
index++;
num = num / 1000;
}
return result.trim();
}
public String getDigit(int num) {
if (num == 0) {
return "";
} else if (num < 20) {
return lessThan20[num] + " ";
} else if (num < 100) {
return tenTh[num / 10] + " " + getDigit(num % 10);
} else {
return lessThan20[num / 100] + " Hundred " + getDigit(num % 100);
}
}
}
// @lc code=end