-
Notifications
You must be signed in to change notification settings - Fork 0
/
integer to english words.py
85 lines (76 loc) · 2.1 KB
/
integer to english words.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# https://leetcode.com/problems/integer-to-english-words/
class Solution:
def numberToWords(self, num: int) -> str:
if num == 0:
return 'Zero'
units = [
'',
'One',
'Two',
'Three',
'Four',
'Five',
'Six',
'Seven',
'Eight',
'Nine',
]
teens = [
'Ten',
'Eleven',
'Twelve',
'Thirteen',
'Fourteen',
'Fifteen',
'Sixteen',
'Seventeen',
'Eighteen',
'Nineteen',
]
tens = [
'',
'',
'Twenty',
'Thirty',
'Forty',
'Fifty',
'Sixty',
'Seventy',
'Eighty',
'Ninety',
]
billions, num = divmod(num, 1_000_000_000)
millions, num = divmod(num, 1_000_000)
thousands, num = divmod(num, 1_000)
def int_to_words(number, postfix=None):
words = []
hundred, number = divmod(number, 100)
ten, number = divmod(number, 10)
if hundred:
words.append(units[hundred])
words.append("Hundred")
if ten == 1:
words.append(teens[number])
elif ten > 1:
words.append(tens[ten])
if number:
words.append(units[number])
else:
if number:
words.append(units[number])
if postfix:
words.append(postfix)
return words
parts = []
if billions:
parts.extend(int_to_words(billions, "Billion"))
if millions:
parts.extend(int_to_words(millions, "Million"))
if thousands:
parts.extend(int_to_words(thousands, "Thousand"))
if num:
parts.extend(int_to_words(num))
return ' '.join(parts)
if __name__ == '__main__':
num = 50868
print(Solution().numberToWords(num))