Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
Example 1:
Input: 123
Output: "One Hundred Twenty Three"
Example 2:
Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"
Example 3:
Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Example 4:
Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
Solution:
class Solution { public String numberToWords(int num) { if (num == 0) return "Zero"; StringBuilder sb = new StringBuilder(); if (num >= (int) 1e9) { int b = num / (int) 1e9; String bStr = words3Digits(b); sb.append(bStr); sb.append(" Billion"); num -= b * (int) 1e9; } if (num >= (int) 1e6) { int m = num / (int) 1e6; String mStr = words3Digits(m); if (sb.length() > 0) sb.append(" "); sb.append(mStr); sb.append(" Million"); num -= m * (int) 1e6; } if (num >= (int) 1e3) { int t = num / (int) 1e3; String tStr = words3Digits(t); if (sb.length() > 0) sb.append(" "); sb.append(tStr); sb.append(" Thousand"); num -= t * (int) 1e3; } if (num > 0) { if (sb.length() > 0) sb.append(" "); sb.append(words3Digits(num)); } return sb.toString(); }
map.put(20, "Twenty"); map.put(30, "Thirty"); map.put(40, "Forty"); map.put(50, "Fifty"); map.put(60, "Sixty"); map.put(70, "Seventy"); map.put(80, "Eighty"); map.put(90, "Ninety"); StringBuilder sb = new StringBuilder(); if (num >= 100) { int h = num / 100; sb.append(map.get(h)); sb.append(" Hundred"); num -= h * 100; } if (num > 10 && num < 20) { if (sb.length() > 0) sb.append(" "); sb.append(map.get(num)); num = 0; } if (num >= 10) { int ty = num / 10; if (sb.length() > 0) sb.append(" "); sb.append(map.get(ty * 10)); num -= ty * 10; } if (num > 0) { int d = num; if (sb.length() > 0) sb.append(" "); sb.append(map.get(d)); } return sb.toString(); } }