解法
难倒是不难,考验细心
坑:
- 单词不要拼错
- 10~19的注意挑出来
- 0的处理
class Solution(object):
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
BILLION = 1000000000
THOUSAND = 1000
MILLION = 1000000
if num==0:
return "Zero"
dic = {
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',
20: 'Twenty',30: 'Thirty',40: 'Forty',50: 'Fifty',60: 'Sixty',70: 'Seventy',80: 'Eighty',90: 'Ninety'
}
def each_thousand(num):
if num == 0:
return ""
hundred = num / 100
ten = num % 100 - num % 10
single = num % 10
hundred = "" if hundred == 0 else "%s Hundred " % dic[hundred]
if ten==10:
ten = "%s "% dic[ten+single]
single = ""
else:
ten = "%s " % dic[ten] if ten!=0 else ""
single = "" if single == 0 else "%s " % dic[single]
return hundred + ten + single
def each_million(num):
if num == 0:
return ""
thousand = each_thousand(num / THOUSAND)
rest = each_thousand(num % THOUSAND)
return ("%sThousand " % thousand if thousand!="" else "")+rest
def each_billion(num):
if num == 0:
return ""
rest = each_million(num % MILLION)
thousands = each_thousand(num/ MILLION)
return ("%sMillion " % thousands if thousands != "" else "") + rest
billions = []
while num:
billions.append(num%BILLION)
num /= BILLION
billions = billions[::-1]
res = ""
for i in billions[:-1]:
string = each_billion(i)
if string != "":
string += 'Billion '
res += string
res += each_billion(billions[-1])
return res.strip()