-
Notifications
You must be signed in to change notification settings - Fork 0
/
273. Integer to English Words.py
37 lines (28 loc) · 1.21 KB
/
273. 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
class Solution:
def __init__(self):
self.lessThan20 = ["","One","Two","Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Eleven",
"Twelve", "Thirteen", "Fourteen", "Fifteen",
"Sixteen", "Seventeen", "Eighteen", "Nineteen"]
self.tens = ["", "Ten", "Twenty", "Thirty", "Forty", "Fifty",
"Sixty", "Seventy", "Eighty", "Ninety"]
self.thousands = ["", "Thousand", "Million", "Billion"]
def numberToWords(self, num):
if num == 0:
return "Zero"
res = ""
for i in range(len(self.thousands)):
if num % 1000 != 0:
res = self.helper(num%1000) + self.thousands[i] + " " + res
num //= 1000
return res.strip()
def helper(self, num):
if num == 0:
return ""
elif num < 20:
return self.lessThan20[num] + " "
elif num < 100:
return self.tens[num//10] + " " + self.helper(num%10)
else:
return self.lessThan20[num//100] + " Hundred " + self.helper(num%100)
print(Solution().numberToWords(123))