H-273. Integer to English Words
# 这可能是全lc最傻逼的题目了
class Solution:
def numberToWords(self, num: int) -> str:
def num_lt_10(num):
num_map = {
1: 'One',
2: 'Two',
3: 'Three',
4: 'Four',
5: 'Five',
6: 'Six',
7: 'Seven',
8: 'Eight',
9: 'Nine'
}
return num_map[num]
def num_lt_20(num):
num_map = {
10: 'Ten',
11: 'Eleven',
12: 'Twelve',
13: 'Thirteen',
14: 'Fourteen',
15: 'Fifteen',
16: 'Sixteen',
17: 'Seventeen',
18: 'Eighteen',
19: 'Nineteen'
}
return num_map[num]
def num_tenth(num):
num_map = {
2: 'Twenty',
3: 'Thirty',
4: 'Forty',
5: 'Fifty',
6: 'Sixty',
7: 'Seventy',
8: 'Eighty',
9: 'Ninety'
}
return num_map[num]
def two_digits(num):
if not num:
return ''
elif num < 10:
return num_lt_10(num)
elif num < 20:
return num_lt_20(num)
else:
q, r = divmod(num, 10)
return num_tenth(q) + ' ' + num_lt_10(r) if r else num_tenth(q)
def three_digits(num):
q, r = divmod(num, 100)
if q and r:
return num_lt_10(q) + ' Hundred ' + two_digits(r)
elif not q and r:
return two_digits(r)
elif q and not r:
return num_lt_10(q) + ' Hundred'
billion = num // 1000000000
million = (num - billion * 1000000000) // 1000000
thousand = (num - billion * 1000000000 - million * 1000000) // 1000
rest = num - billion * 1000000000 - million * 1000000 - thousand * 1000
if not num:
return 'Zero'
result = ''
if billion:
result = three_digits(billion) + ' Billion'
if million:
result += ' ' if result else ''
result += three_digits(million) + ' Million'
if thousand:
result += ' ' if result else ''
result += three_digits(thousand) + ' Thousand'
if rest:
result += ' ' if result else ''
result += three_digits(rest)
return result
Last updated
Was this helpful?