难度:困难
题目描述:
思路:递归做法,这个真不是一般能想到的,需要仔细体会,膜拜大佬吧,以后如果中文力扣没有满意的题解,去英文相应题一定能找到比较trick的题解。
class Solution:
def numberToWords(self, num: int) -> str:
to19 = 'One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve ' \
'Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split()
tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split()
def helper(num):
if num < 20:
return to19[num - 1:num]
if num < 100:
return [tens[num // 10 -2]] + helper(num % 10)
if num < 1000:
return [to19[num // 100 - 1]] + ["Hundred"] + helper(num % 100)
for p, w in enumerate(["Thousand", "Million", "Billion"], 1):
if num < 1000 ** (p + 1):
return helper(num // 1000 ** p) + [w] + helper(num % 1000 ** p)
return " ".join(helper(num)) or "Zero"
提交结果:
参考资料: