|
| 1 | +class Solution { |
| 2 | + private static Map<Integer, String> map; |
| 3 | + |
| 4 | + static { |
| 5 | + map = new HashMap<>(); |
| 6 | + map.put(1, "One"); |
| 7 | + map.put(2, "Two"); |
| 8 | + map.put(3, "Three"); |
| 9 | + map.put(4, "Four"); |
| 10 | + map.put(5, "Five"); |
| 11 | + map.put(6, "Six"); |
| 12 | + map.put(7, "Seven"); |
| 13 | + map.put(8, "Eight"); |
| 14 | + map.put(9, "Nine"); |
| 15 | + map.put(10, "Ten"); |
| 16 | + map.put(11, "Eleven"); |
| 17 | + map.put(12, "Twelve"); |
| 18 | + map.put(13, "Thirteen"); |
| 19 | + map.put(14, "Fourteen"); |
| 20 | + map.put(15, "Fifteen"); |
| 21 | + map.put(16, "Sixteen"); |
| 22 | + map.put(17, "Seventeen"); |
| 23 | + map.put(18, "Eighteen"); |
| 24 | + map.put(19, "Nineteen"); |
| 25 | + map.put(20, "Twenty"); |
| 26 | + map.put(30, "Thirty"); |
| 27 | + map.put(40, "Forty"); |
| 28 | + map.put(50, "Fifty"); |
| 29 | + map.put(60, "Sixty"); |
| 30 | + map.put(70, "Seventy"); |
| 31 | + map.put(80, "Eighty"); |
| 32 | + map.put(90, "Ninety"); |
| 33 | + map.put(100, "Hundred"); |
| 34 | + map.put(1000, "Thousand"); |
| 35 | + map.put(1000000, "Million"); |
| 36 | + map.put(1000000000, "Billion"); |
| 37 | + } |
| 38 | + |
| 39 | + public String numberToWords(int num) { |
| 40 | + if (num == 0) { |
| 41 | + return "Zero"; |
| 42 | + } |
| 43 | + StringBuilder sb = new StringBuilder(); |
| 44 | + for (int i = 1000000000; i >= 1000; i /= 1000) { |
| 45 | + if (num >= i) { |
| 46 | + sb.append(get3Digits(num / i)).append(' ').append(map.get(i)); |
| 47 | + num %= i; |
| 48 | + } |
| 49 | + } |
| 50 | + if (num > 0) { |
| 51 | + sb.append(get3Digits(num)); |
| 52 | + } |
| 53 | + return sb.substring(1); |
| 54 | + } |
| 55 | + |
| 56 | + private String get3Digits(int num) { |
| 57 | + StringBuilder sb = new StringBuilder(); |
| 58 | + if (num >= 100) { |
| 59 | + sb.append(' ').append(map.get(num / 100)).append(' ').append(map.get(100)); |
| 60 | + num %= 100; |
| 61 | + } |
| 62 | + if (num > 0) { |
| 63 | + if (num < 20 || num % 10 == 0) { |
| 64 | + sb.append(' ').append(map.get(num)); |
| 65 | + } else { |
| 66 | + sb.append(' ').append(map.get(num / 10 * 10)).append(' ').append(map.get(num % 10)); |
| 67 | + } |
| 68 | + } |
| 69 | + return sb.toString(); |
| 70 | + } |
| 71 | +} |
0 commit comments