Integer to English Words
Problem: Integer to English Words
In this problem, we can divide digits into group of three and deal with each group first than do with thousand, million or billion. Besides, we need to deal with 0 too.
Code in Python:
class Solution(object):
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
dict1 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
dict2 = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
dict3 = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
dict4 = ["Thousand", "Million", "Billion"]
def helper(num):
ans = ""
if num == 0: return ans
if num/100 != 0:
ans += dict1[num/100] + " Hundred "
num = num % 100
if num >= 10 and num < 20: ans += dict3[num-10] + " "
else:
if num/10 != 0:
ans += dict2[num/10] + " "
num = num % 10
if num != 0:
ans += dict1[num] + " "
return ans
if not num: return "Zero"
i, ans = 0, ""
ans = helper(num%1000) + ans
while num/1000:
num = num / 1000
if num % 1000 != 0:
ans = helper(num%1000) + dict4[i] + " " + ans
i += 1
return ans[:len(ans)-1]