We divide the number every 4 digits,
for each interval, it's xxx hundreds + ( xxxty + number < 10) or (number < 20) + Thousands/millions/billions/""
we get the number in each interval by %1000. if %1000 == 0 then we skip this loop.
if input == 0 just return "zero" (because we don't have other place to use zero.)
Code:
class Solution {
private final String[] SPECIALS = {"","One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private final String[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty","Seventy", "Eighty", "Ninety"};
private final String[] THOUSANDS = {"", "Thousand", "Million", "Billion"};
public String result = "";
public String numberToWords(int num) {
int bit = 0;
if(num == 0) return "Zero";
while(num != 0){
int value = num % 1000;
if(value != 0){
result = helper(value) +" "+ THOUSANDS[bit] + " "+ result.trim();
}
num = num/1000;
bit++;
}
return result.trim();
}
public String helper(int num) {
String s = "";
int hundred = num / 100;
if(hundred != 0){
s = SPECIALS[hundred] + " Hundred ";
num = num % 100;
}
if(num < 20){
s = s + SPECIALS[num];
}else{
s = s + TENS[num/10] +" "+ SPECIALS[num%10];
}
return s.trim();
}
}