- 整数转换英文表示
将非负整数转换为其对应的英文表示。可以保证给定输入小于 231 - 1 。
示例 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”
头一次自己写hard,感觉蛮有思路的(当然无法和大牛相比,我就是棵小白菜)。
如果这个题用map会方便点吧,但懒得打,还是list走起。
思路:纯按我自己读英文数字的方式。
先逗号分好了(一个逗号一个读法),隔间里面的都按三位数的读。
代码主要分了两部分:一个是隔间里几百几十几的读法(这部分写得不是很顺),另一个是隔间里的数读好后怎么把逗号的读法插进去。
譬如: 111,022,000,100 【中文念我都要数半天!
class Solution:
def numberToWords(self, num: int) -> str:
if num==0: return "Zero"
lst_1_19 = 'One Two Three Four Five Six Seben Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split()
lst_20_90 = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split()
lst = format(num,',').split(',')
#111002000100: ['111', '022', '000', '100']
n = len(lst) # 1 <= n <= 4
def word_000(num):
# 000 - 999
_res = ''
num = int(num)
if num//100 != 0: #100-999
_res += word_000(num//100) + ' Hundred '
num %= 100
if num//10 > 1 : #20-99
_res += lst_20_90[num//10 - 2] + ' '
num %= 10
if num != 0 : #1-19
_res += lst_1_19[num-1]
return _res.strip()
lst_000 = list(map(word_000, lst))
#['One Hundred Eleven', 'Twenty Two', '', 'One Hundred']
lst_comma = ['Thousand', 'Million' ,'Billion']
res = []
count = 0
for i in range(n-1, -1, -1): #(3,(2,(1,(0
res.append(lst_000[i])
if i == 0: break
res.append(lst_comma[count]) if lst_000[i-1] else ''
count += 1
#res[::-1] = ['One Hundred Eleven', 'Billion', 'Twenty Two', 'Million', '', 'One Hundred']
return ' '.join(list(filter(None, res))[::-1])
复习日重写:
class Solution:
def numberToWords(self, num: int) -> str:
if num == 0: return 'Zero'
num_lst = format(num,',').split(',')
under20_lst = ['One',
'Two',
'Three',
'Four',
'Five',
'Six',
'Seven',
'Eight',
'Nine',
'Ten',
'Eleven',
'Twelve',
'Thirteen',
'Fourteen',
'Fifteen',
'Sixteen',
'Seventeen',
'Eighteen',
'Nineteen']
under100_lst = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
def read(n):
# >=100
if n >= 100:
l, r = divmod(n,100)
return read(l) + ' Hundred ' +read(r)
# 20 - 99
if 20 <= n <= 99:
l, r = divmod(n,10)
return under100_lst[l-2] + ' ' + read(r)
# 1- 19
if 0 < n <= 19:
return under20_lst[n-1]
if n == 0:
return ''
mylist = [read(int(_)).strip() for _ in num_lst]
#mylist = ['a' ,'b' ,'' ,'c']
comma_list = ['Thousand','Million','Billion']
res = []
j = 0
for i in range(len(mylist)-1,-1, -1):
if mylist[i]:
res.append(mylist[i])
if i - 1 >= 0 and mylist[i - 1]:
res.append(comma_list[j])
j += 1
return ' '.join(res[::-1])