解题思路主要基于对数字的逐段解析,将整数划分为若干三位数的段,每个段内单独处理,并转换为英文表述。首先定义四个列表,分别表示个位数、十位数中的特殊情况(10到19)、普通的十位数后缀(20, 30, ...),以及千位数的后缀(千、百万、十亿)。主要函数使用递归处理每个三位数的段,再将这些段结合千位数后缀组合起来形成完整的英文表述。递归函数处理小于10的数返回对应的英文,处理小于20的数返回特殊的青少年数字英文,处理小于100的数将十位和个位分开处理,处理三位数时将百位、十位和个位分开处理。整个数按千的倍数逐步减少,每处理完一个三位数的段,就添加相应的千位后缀。
时间复杂度: O(n)
空间复杂度: O(1)
singles = ["", "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"
def recur(num: int) -> str:
s = ""
if num == 0:
return s
elif num < 10:
s += singles[num] + " "
elif num < 20:
s += teens[num - 10] + " "
elif num < 100:
s += tens[num // 10] + " " + recur(num % 10)
else:
s += singles[num // 100] + " Hundred " + recur(num % 100)
return s
s = ""
unit = int(1e9)
for i in range(3, -1, -1):
cur_num = num // unit
if cur_num:
num -= cur_num * unit
s += recur(cur_num) + thousands[i] + " "
unit //= 1000
return s.strip()