Convert a non-negative integer num
to its English words representation.
Example 1:
Input: num = 123 Output: "One Hundred Twenty Three"
Example 2:
Input: num = 12345 Output: "Twelve Thousand Three Hundred Forty Five"
Example 3:
Input: num = 1234567 Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Constraints:
0 <= num <= 2^31 - 1
题目要求把一个非负整数转换成英文表达。
根据限制条件我们知道给定的是一个32位非负整数,即范围是0~2147483647,也就是说最大就是10亿(Billion)级别的。另外我们知道英文对数的书写是每隔三位用一个逗号,即每隔三位换一种表达(Thousand, Million, Billion)。也因此一个数的每一位的英文表达是:个、十,百、个千、十千、百千、个百万、十百万、百百万、个十亿、十十亿、百十亿。规律就是每三位的表达其实是一样的都是:个、十、百,区别只是后边根据所在的数级别分别加:'', 'Thousand', 'Million', 'Billion'。
因此,我们只要实现一个三位数处理函数把“个十百”转换成英文表达,然后把输入数按‘1,000,000,000’, '1,000,000', '1,000'的级别进行划分,依次调用三位数处理函数,后面再依次加上'Billion', 'Million', 'Thousand'。
三位数的处理,根据英文表达可以把一个三位数分为大于等于100,大于等于20,大于0三种来分别处理。
注如果输入是0,就直接返回“Zero”。
class Solution:
def numberToWords(self, num: int) -> str:
if num == 0:
return "Zero"
list1 = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
list2 = ["Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
def ThreeDigitSToWords(d):
res = []
if d >= 100:
res.append(list1[d // 100])
res.append("Hundred")
d %= 100
if d >= 20:
res.append(list2[d // 10 - 1])
if d % 10 > 0:
res.append(list1[d % 10])
elif d > 0:
res.append(list1[d])
return ' '.join(res)
ans = []
if num >= 10**9:
ans.append(ThreeDigitSToWords(num // (10 ** 9)))
ans.append("Billion")
num %= 10 ** 9
if num >= 10**6:
ans.append(ThreeDigitSToWords(num // (10 ** 6)))
ans.append("Million")
num %= 1000000
if num >= 1000:
ans.append(ThreeDigitSToWords(num // (1000)))
ans.append("Thousand")
num %= 1000
if num > 0:
ans.append(ThreeDigitSToWords(num))
return ' '.join(ans)