目录

0273:整数转换英文表示(★★)

力扣第 273 题

题目

将非负整数 num 转换为其对应的英文表示。

示例 1:

输入:num = 123
输出:"One Hundred Twenty Three"

示例 2:

输入:num = 12345
输出:"Twelve Thousand Three Hundred Forty Five"

示例 3:

输入:num = 1234567
输出:"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

提示:

  • 0 <= num <= 231 - 1

相似问题:

分析

用递归比较方便,注意特判 num 为 0 返回 Zero。

解答

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def numberToWords(self, num: int) -> str:
        A = [(10**9,'Billion'),(10**6,'Million'),(1000,'Thousand'),(100,'Hundred')]
        B = ['Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety']
        C = ['One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten', 
            'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen',
            'Seventeen', 'Eighteen', 'Nineteen']
        def dfs(x):
            for w,s in A:
                if x>=w:
                    return dfs(x//w)+[s]+dfs(x%w)
            if x>=20:
                return [B[x//10-2]]+dfs(x%10)
            return [C[x-1]] if x else []
        return ' '.join(dfs(num)) or 'Zero'

30 ms