Problem Statement
(Source) 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”
Analysis
Split the input number into groups of 3 digits from lowest bit to highest bit. Then process each group and add corresponding units to the result of each group. Combine sub-answer to get the final global answer.
Solution
class Solution(object):
def process(self, map1, map2, num):
"""Process a non-negtive number which contains no more than 3 digits.
"""
if num == 0:
return ''
elif num < 20:
return map1[num]
elif num >= 20 and num <= 99:
ans = map2[num / 10]
if num % 10:
ans = ans + ' ' + map1[num % 10]
return ans
else:
ans = map1[num / 100] + ' Hundred'
if num % 100:
ans = ans + ' ' + self.process(map1, map2, num % 100)
return ans
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return 'Zero'
res = []
map1 = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen'}
map2 = {2: 'Twenty', 3: 'Thirty', 4: 'Forty', 5: 'Fifty', 6: 'Sixty', 7: 'Seventy', 8: 'Eighty', 9: 'Ninety'}
unit_map = {1: 'Thousand', 2: 'Million', 3: 'Billion'}
unit = 0
while num:
x = num % 1000
sub_ans = self.process(map1, map2, x)
if sub_ans:
if unit:
sub_ans = sub_ans + ' ' + unit_map[unit]
res.append(sub_ans)
num /= 1000
unit += 1
res.reverse()
return ' '.join(res)