LeetCode 题解工作台
反转之后的数字和
给你一个 非负 整数 num 。如果存在某个 非负 整数 k 满足 k + reverse(k) = num ,则返回 true ;否则,返回 false 。 reverse(k) 表示 k 反转每个数位后得到的数字。 示例 1: 输入: num = 443 输出: true 解释: 172 + 2…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数学·结合·enumeration
答案摘要
在 $[0,.., num]$ 范围内枚举 ,判断 $k + reverse(k)$ 是否等于 即可。 时间复杂度 $O(n \times \log n)。其中 为 的大小。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·enumeration 题型思路
题目描述
给你一个 非负 整数 num 。如果存在某个 非负 整数 k 满足 k + reverse(k) = num ,则返回 true ;否则,返回 false 。
reverse(k) 表示 k 反转每个数位后得到的数字。
示例 1:
输入:num = 443 输出:true 解释:172 + 271 = 443 ,所以返回 true 。
示例 2:
输入:num = 63 输出:false 解释:63 不能表示为非负整数及其反转后数字之和,返回 false 。
示例 3:
输入:num = 181 输出:true 解释:140 + 041 = 181 ,所以返回 true 。注意,反转后的数字可能包含前导零。
提示:
0 <= num <= 105
解题思路
方法一:暴力枚举
在 范围内枚举 ,判断 是否等于 即可。
时间复杂度 nnum$ 的大小。
class Solution:
def sumOfNumberAndReverse(self, num: int) -> bool:
return any(k + int(str(k)[::-1]) == num for k in range(num + 1))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(num * k) where k is the number of digits in each candidate number, due to enumerating up to num and reversing each number. Space complexity is O(k) for temporary storage of the reversed number, either as string or digits array. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if candidate x plus its reverse equals num
- question_mark
Expect early exit once solution is found
- question_mark
Consider how leading zeros affect the reversed number sum
常见陷阱
外企场景- error
Ignoring leading zeros when reversing numbers
- error
Assuming only certain ranges of x need checking
- error
Not exiting early after finding a valid pair
进阶变体
外企场景- arrow_right_alt
Find all x values that satisfy x plus reverse(x) equals num
- arrow_right_alt
Restrict x to even or odd numbers and check sum
- arrow_right_alt
Apply same logic to arrays where each element must satisfy the sum-with-reverse condition