給定一個(gè)整數(shù)唬滑,輸出英文表示建邓。
將整數(shù)轉(zhuǎn)換成英文表示中支鸡,將數(shù)字按照 3 位一組劃分怀樟,將每一組的英文表示拼接之后即可得到整數(shù)num 的英文表示碍侦。
每一組最多有3 位數(shù)矿微,可以使用遞歸的方式得到每一組的英文表示呐能。根據(jù)數(shù)字所在的范圍念搬,具體做法如下:
- 小于20 的數(shù)可以直接得到其英文表示;
- 大于等于20 且小于100 的數(shù)首先將十位轉(zhuǎn)換成英文表示摆出,然后對(duì)個(gè)位遞歸地轉(zhuǎn)換成英文表示朗徊;
- 大于等于100 的數(shù)首先將百位轉(zhuǎn)換成英文表示,然后對(duì)其余部分(十位和個(gè)位)遞歸地轉(zhuǎn)換成英文表示偎漫。
singles = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
teens = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
tens = ["", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
thousands = ["", "Thousand", "Million", "Billion"]
class Solution:
def numberToWords(self, num: int) -> str:
if num == 0:
return "Zero"
nums, base = [], []
index = 0
while num > 0:
n = num % 1000
nums.append(self.num_to_str(n))
base.append(thousands[index])
num //= 1000
index += 1
nums = nums[::-1]
base = base[::-1]
res = []
for i in range(len(nums)):
if len(nums[i]) > 0:
res.append(nums[i])
res.append(base[i])
if res[-1] == "":
return " ".join(res[:-1])
else:
return " ".join(res)
def num_to_str_2digits(self, num):
res = []
if 1 <= num <= 9:
res.append(singles[num])
elif 10 <= num <= 19:
res.append(teens[num-10])
elif 20 <= num < 100:
res.append(tens[num // 10])
if num % 10 >= 1:
res.append(singles[num%10])
return res
def num_to_str(self, num):
a = num // 100
b = num % 100
res = []
if a > 0:
res.append(singles[a])
res.append("Hundred")
res += self.num_to_str_2digits(b)
return " ".join(res)