leetcode 273. 整数转换英文表示

解题思路

模拟 “整数” 转换为 “英文”
注意:100 转换结果为 One Hundred

代码

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
86
87
class Solution:
def numberToWords(self, num: int) -> str:
if num == 0:
return 'Zero'

result = ''

billion = num // 1000000000
million = (num % 1000000000) // 1000000
thousand = (num % 1000000) // 1000
rest = num % 1000

if billion:
result += self.three(billion) + ' Billion'
if million:
result += result and ' ' or ''
result += self.three(million) + ' Million'
if thousand:
result += result and ' ' or ''
result += self.three(thousand) + ' Thousand'
if rest:
result += result and ' ' or ''
result += self.three(rest)

return result

def three(self, num):
hundred = num // 100
rest = num % 100
if hundred and rest:
return self.one(hundred) + ' Hundred ' + self.two(rest)
if not hundred and rest:
return self.two(rest)
if hundred and not rest:
return self.one(hundred) + ' Hundred'

def one(self, num):
switcher = {
1: 'One',
2: 'Two',
3: 'Three',
4: 'Four',
5: 'Five',
6: 'Six',
7: 'Seven',
8: 'Eight',
9: 'Nine'
}
return switcher.get(num)

def two(self, num):
if num < 10:
return self.one(num)
if num < 20:
return self.two_less_20(num)
else:
tenner = num // 10
rest = num % 10
return rest and self.ten(tenner) + ' ' + self.one(rest) or self.ten(tenner)

def two_less_20(self, num):
switcher = {
10: 'Ten',
11: 'Eleven',
12: 'Twelve',
13: 'Thirteen',
14: 'Fourteen',
15: 'Fifteen',
16: 'Sixteen',
17: 'Seventeen',
18: 'Eighteen',
19: 'Nineteen'
}
return switcher.get(num)

def ten(self, num):
switcher = {
2: 'Twenty',
3: 'Thirty',
4: 'Forty',
5: 'Fifty',
6: 'Sixty',
7: 'Seventy',
8: 'Eighty',
9: 'Ninety'
}
return switcher.get(num)