Re: [闲聊] 每日leetcode

楼主: dont   2024-08-07 08:55:45
273. Integer to English Words
## 思路
列出所有可能的英文字
1~19, 十位数, 百/千/百万/十亿
Input: num = 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty
Seven"
1,234,567 = 1 Million + 234 Thousand + 567
234 = 2 Hundred + 30 + 4
567 = 5 Hundred + 60 + 7
把数字照10**9, 10**6, 10**3, 100顺序切割做recursion转换成英文
## Code
```python
class Solution:
def numberToWords(self, num: int) -> str:
if num == 0:
return 'Zero'
to19 = (',One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,'
'Eleven,Twelve,Thirteen,Fourteen,Fifteen,Sixteen,'
'Seventeen,Eighteen,Nineteen').split(',')
tens =
(',Ten,Twenty,Thirty,Forty,Fifty,Sixty,Seventy,Eighty,Ninety').split(',')
split_pairs = [
(1_000_000_000, 'Billion'),
(1_000_000, 'Million'),
(1_000, 'Thousand'),
(100, 'Hundred'),
]
def get_word(num):
res = []
for val, word in split_pairs:
if num >= val:
chunk, num = divmod(num, val)
res.append(get_word(chunk))
res.append(word)
if num >= 20:
chunk, num = divmod(num, 10)
res.append(tens[chunk])
if num > 0:
res.append(to19[num])
return ' '.join(res)
return get_word(num)
```

Links booklink

Contact Us: admin [ a t ] ucptt.com