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 54
| class Solution { public String numberToWords(int num) { if(num==0) return "Zero"; String ans = ""; while(num>0){ if(num>=1000000000){ int billionNum = num/1000000000; ans = ans + computeNumLessThousand(billionNum) + "Billion "; num = num % 1000000000; } else if(num>=1000000){ int millionNum = num/1000000; ans = ans + computeNumLessThousand(millionNum) + "Million "; num = num % 1000000; } else if(num>=1000){ int thousandNum = num/1000; ans = ans + computeNumLessThousand(thousandNum) + "Thousand "; num = num % 1000; } else{ ans = ans + computeNumLessThousand(num); break; } } ans = ans.substring(0, ans.length()-1); return ans; } private String computeNumLessThousand(int num){ String[] digits = new String[]{"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; String[] tens = new String[]{"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; String ans = ""; while(num>0){ if(num>=100){ int hundredNum = num/100; ans = ans + computeNumLessThousand(hundredNum) + "Hundred "; num = num %100; } else if(num>=20){ int tensNum = num/10; ans = ans + tens[tensNum] + " "; num = num %10; } else { ans = ans + digits[num] + " "; break; } } return ans; } }
|