1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
| class Solution:
def numberToWords(self, num: int) -> str:
if num == 0:
return 'Zero'
lt20 = [
'',
'One',
'Two',
'Three',
'Four',
'Five',
'Six',
'Seven',
'Eight',
'Nine',
'Ten',
'Eleven',
'Twelve',
'Thirteen',
'Fourteen',
'Fifteen',
'Sixteen',
'Seventeen',
'Eighteen',
'Nineteen',
]
tens = [
'',
'Ten',
'Twenty',
'Thirty',
'Forty',
'Fifty',
'Sixty',
'Seventy',
'Eighty',
'Ninety',
]
thousands = ['Billion', 'Million', 'Thousand', '']
def transfer(num):
if num == 0:
return ''
if num < 20:
return lt20[num] + ' '
if num < 100:
return tens[num // 10] + ' ' + transfer(num % 10)
return lt20[num // 100] + ' Hundred ' + transfer(num % 100)
res = []
i, j = 1000000000, 0
while i > 0:
if num // i != 0:
res.append(transfer(num // i))
res.append(thousands[j])
res.append(' ')
num %= i
j += 1
i //= 1000
return ''.join(res).strip()
|