**Input:** num = 123
**Output:** "One Hundred Twenty Three"
**Input:** num = 12345
**Output:** "Twelve Thousand Three Hundred Forty Five"
**Input:** num = 1234567
**Output:** "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
**Input:** num = 1234567891
**Output:** "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
it's very heavy dirty code writing.
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[] tens = new String[]{"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
private String[] thousands = new String[]{"", "Thousand", "Million", "Billion"};
public String numberToWords(int num) {
// edge cases
if (num == 0) return "Zero";
String res = "";
int kth = 0;
while (num > 0) {
int tmp = num % 1000;
if (tmp != 0) {
res = read3(tmp) + " " + thousands[kth] + " " + res;
}
num /= 1000;
kth++;
}
return res.trim();
}
private String read3(int num) {
StringBuilder sb = new StringBuilder();
int d1 = num % 10;
int d2 = (num % 100) / 10;
int d3 = num / 100;
// read hundred
if (d3 != 0) {
sb.append(lessThan20[d3] + " Hundred");
}
// read tens
if (d2 != 0) {
int last2digit = num % 100;
if (last2digit < 20) {
sb.append(" " + lessThan20[last2digit]);
return sb.toString().trim();
} else {
sb.append(" " + tens[d2]);
}
}
// read one
if (d1 != 0) {
sb.append(" " + lessThan20[d1]);
}
return sb.toString().trim();
}
}
/*
2,147,483,647
1st: 647
2nd: 483
3rd: 147
4th: 2
*/