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
| class Solution { public String numberToWords(int num) { if(num==0) return "Zero"; return convert(num).substring(0); } private static String convert(int num){ String kUnder20[] = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine","Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; String kUnder100[] = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; String kHTMB[] = {"Hundred", "Thousand", "Million", "Billion"}; int kP[] = {100, 1000, 1000*1000, 1000*1000*1000}; if(num == 0) return ""; if(num<20) { String result = kUnder20[num-1]; return result; } if(num>=20&&num<100){ String result = kUnder100[num/10-2]; if(num%10>0) result = result +" "; return result+convert(num%10); } for(int i=3;i>=0;i--) if(num>=kP[i]) return concat(convert(num/kP[i])+" "+ kHTMB[i],convert(num%kP[i])); return ""; } private static String concat(String s1, String s2) { return s1 == "" ? s2 : s2 == "" ? s1 : s1 + " " + s2; } }
|