给定一个整数,打印该整数的英文描述。
示例 1:
输入: 123
输出: "One Hundred Twenty Three"
示例 2:
输入: 12345
输出: "Twelve Thousand Three Hundred Forty Five"
示例 3:
输入: 1234567
输出: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
示例 4:
输入: 1234567891
输出: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
Python 解答:
class Solution:
def numberToWords(self, num: int) -> str:
maps = {'0':"Zero", '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'}
units = ['Thousand', 'Million', 'Billion']
def trans3digit(bits):
if not bits:
return ""
if len(bits) == 1:
return maps[bits]
elif len(bits) == 2:
if bits[0] == '0' and bits[1] == '0':
return ""
elif bits[0] == '0' and bits[1] != '0':
return maps[bits[1]]
elif bits[0] == '1' or bits[1] == '0':
return maps[bits]
else:
return maps[bits[0]+'0'] +' '+ maps[bits[1]]
elif len(bits) == 3:
if bits[0] == '0' and bits[1] == '0' and bits[2] == '0':
return ""
elif bits[0] != '0' and bits[1] == '0' and bits[2] == '0':
return maps[bits[0]]+' '+'Hundred'
elif bits[0] == '0':
return trans3digit(bits[1:])
else:
return maps[bits[0]]+' '+'Hundred'+' '+trans3digit(bits[1:])
string = str(num)
length = len(string)
i = -1
res = ""
while length > 0:
j = length
k = length-3 if length-3 >= 0 else 0
if i == -1:
res = trans3digit(string[k:j])+ res
else:
temp = trans3digit(string[k:j])
if temp and res:
res = temp+' '+units[i]+' '+ res
elif temp:
res = temp+' '+units[i]
length -= 3
i += 1
return res
留言