Leetcode[273] Integer to English Words
02 Dec 2015###Task1 Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
For example, 123 -> “One Hundred Twenty Three” 12345 -> “Twelve Thousand Three Hundred Forty Five” 1234567 -> “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven” Hint:
Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.
Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.
There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)
###Python
class Solution(object):
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return 'Zero'
nums = []
ret = []
levels = ['', 'Thousand ', 'Million ', 'Billion ']
while num > 0:
nums.append(num % 1000)
num /= 1000
for i in range(len(nums)):
cur = self.convert(nums[i])
if nums[i] != 0:
cur += levels[i]
ret.append(cur)
return ''.join(reversed(ret)).rstrip(' ')
def convert(self, n):
ones = ['Zero', 'One ', 'Two ', 'Three ', 'Four ', 'Five ', 'Six ', 'Seven ', 'Eight ', 'Nine ', 'Ten ', 'Eleven ', 'Twelve ', 'Thirteen ', 'Fourteen ', 'Fifteen ', 'Sixteen ', 'Seventeen ', 'Eighteen ', 'Nineteen ']
tens = ['Twenty ', 'Thirty ', 'Forty ', 'Fifty ', 'Sixty ', 'Seventy ', 'Eighty ', 'Ninety ']
cur = ''
if n == 0:
return ''
if n < 20:
cur += ones[n]
elif n < 100:
cur += tens[n / 10 - 2]
cur += self.convert(n % 10)
else:
cur += ones[n / 100] + 'Hundred '
cur += self.convert(n % 100)
return cur
###Java
public class Solution {
public String helper(int cur, String[] dict1, String[] dict2) {
int a = cur / 100;
int b = cur % 100;
int c = cur % 10;
StringBuilder sb = new StringBuilder();
if (a > 0) {
sb.insert(0, dict1[a] + "Hundred ");
}
if (b > 0 && b < 20) {
sb.append(dict1[b]);
c = 0;
} else {
sb.append(dict2[b / 10]);
}
if (c > 0) {
sb.append(dict1[c]);
}
return sb.toString();
}
public String numberToWords(int num) {
if (num == 0) {
return "Zero";
}
String[] arr1 = {"", "Thousand ", "Million ", "Billion "};
String[] dict1 = {"", "One ", "Two ", "Three ", "Four ",
"Five ", "Six ", "Seven ", "Eight ", "Nine ",
"Ten ", "Eleven ", "Twelve ", "Thirteen ",
"Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ",
"Eighteen ", "Nineteen "};
String[] dict2 = {"", "", "Twenty ", "Thirty ", "Forty ", "Fifty ",
"Sixty ", "Seventy ", "Eighty ", "Ninety "};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
int cur = num % 1000;
if (cur > 0) {
sb.insert(0, arr1[i]);
sb.insert(0, helper(cur, dict1, dict2));
}
num /= 1000;
}
String res = sb.toString();
if (res.charAt(res.length() - 1) == ' ') {
res = res.substring(0, res.length() - 1);
}
return res;
}
}
###Points
- Edge cases: if middle contains three 0;
- Recursive call the convert part
- Remove empty spaces in string