LeetCode 题解工作台
整数转换英文表示
将非负整数 num 转换为其对应的英文表示。 示例 1: 输入: num = 123 输出: "One Hundred Twenty Three" 示例 2: 输入: num = 12345 输出: "Twelve Thousand Three Hundred Forty Five" 示例 3: 输…
3
题型
7
代码语言
3
相关题
当前训练重点
困难 · 数学·string
答案摘要
class Solution: def numberToWords(self, num: int) -> str:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路
题目描述
将非负整数 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
解题思路
方法一
class Solution:
def numberToWords(self, num: int) -> str:
if num == 0:
return 'Zero'
lt20 = [
'',
'One',
'Two',
'Three',
'Four',
'Five',
'Six',
'Seven',
'Eight',
'Nine',
'Ten',
'Eleven',
'Twelve',
'Thirteen',
'Fourteen',
'Fifteen',
'Sixteen',
'Seventeen',
'Eighteen',
'Nineteen',
]
tens = [
'',
'Ten',
'Twenty',
'Thirty',
'Forty',
'Fifty',
'Sixty',
'Seventy',
'Eighty',
'Ninety',
]
thousands = ['Billion', 'Million', 'Thousand', '']
def transfer(num):
if num == 0:
return ''
if num < 20:
return lt20[num] + ' '
if num < 100:
return tens[num // 10] + ' ' + transfer(num % 10)
return lt20[num // 100] + ' Hundred ' + transfer(num % 100)
res = []
i, j = 1000000000, 0
while i > 0:
if num // i != 0:
res.append(transfer(num // i))
res.append(thousands[j])
res.append(' ')
num %= i
j += 1
i //= 1000
return ''.join(res).strip()
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(K) |
| 空间 | O(\log_{10} N) |
面试官常问的追问
外企场景- question_mark
Assess if the candidate can handle large numbers effectively by breaking them into manageable chunks.
- question_mark
Evaluate if the candidate understands how to handle special cases, like 0 or numbers involving 'and'.
- question_mark
Look for clarity in the recursive approach and their ability to manage different word mappings.
常见陷阱
外企场景- error
Failing to account for edge cases such as zero or numbers that require 'and' in their English phrasing.
- error
Overcomplicating the problem with unnecessary recursion or overly complex data structures.
- error
Misplacing word mappings, particularly for numbers between 10 and 19, or for powers of ten.
进阶变体
外企场景- arrow_right_alt
Convert to words in a different language or format, expanding the scope of number representation.
- arrow_right_alt
Implement a version without recursion, relying only on iterative or loop-based solutions.
- arrow_right_alt
Extend the problem to handle floating-point numbers or decimals in the conversion.