原题
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”
解法
参考: https://leetcode.com/problems/integer-to-english-words/discuss/70688/Python-Clean-Solution
将所有可能的单词分组成为3个列表, 然后从尾部开始每三位进行读取, 使用遍历和递归. 例如: 1234567891, 先读取891, 得到res是’Eight Hundred Ninety One ', 然后读取567, 得到’Five Hundred Sixty Seven Thousand ', 加上之前的res, 结果是’Five Hundred Sixty Seven Thousand Eight Hundred Ninety One ', , 依次类推.
代码
class Solution(object):
def __init__(self):
self.lessThan20 = ["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"]
self.tens = ["","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"]
self.thousands = ["","Thousand","Million","Billion"]
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return 'Zero'
res = ''
for i in range(len(self.thousands)):
if num % 1000 != 0:
res = self.helper(num % 1000) + self.thousands[i] + ' '+ res
num = num//1000
return res.strip()
def helper(self, num):
if num == 0:
return ''
if num < 20:
return self.lessThan20[num] + ' '
if num < 100:
return self.tens[num//10] + ' '+ self.helper(num%10)
else:
return self.lessThan20[num//100] + ' Hundred ' + self.helper(num%100)