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 46 47 48 49 50 51 52 53
| class Solution { public String numberToWords(int num) { if (num == 0) return "Zero";
int billions = num/1000000000; num %= 1000000000;
int millions = num/1000000; num %= 1000000;
int thousands = num/1000; num %= 1000;
StringBuilder string = new StringBuilder(); if (billions > 0) string.append(helper(billions) + "Billion "); if (millions > 0) string.append(helper(millions) + "Million "); if (thousands > 0) string.append(helper(thousands) + "Thousand "); if (num > 0) string.append(helper(num));
return string.toString().trim();
}
public String helper(int num) { String[] numbers = { "", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen " };
String[] tens = { "", "", "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety " };
int hundred = num/100; num %= 100;
StringBuilder string = new StringBuilder(); if (hundred != 0) string.append(numbers[hundred] + "Hundred ");
if (num < 20) { string.append(numbers[num]); } else { string.append(tens[num/10] + numbers[num%10]); }
return string.toString(); } }
|