LeetCode 题解工作台
回文数
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。 回文数 是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 例如, 121 是回文,而 123 不是。 示例 1: 输入: x = 121 输出: true 示例 2: 输入: x = -121 输出:…
1
题型
10
代码语言
3
相关题
当前训练重点
简单 · 数学·driven
答案摘要
我们先判断特殊情况: - 如果 $x \lt 0$,那么 不是回文数,直接返回 `false`;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
- 例如,
121是回文,而123不是。
示例 1:
输入:x = 121 输出:true
示例 2:
输入:x = -121 输出:false 解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入:x = 10 输出:false 解释:从右向左读, 为 01 。因此它不是一个回文数。
提示:
-231 <= x <= 231 - 1
进阶:你能不将整数转为字符串来解决这个问题吗?
解题思路
方法一:反转一半数字
我们先判断特殊情况:
- 如果 ,那么 不是回文数,直接返回
false; - 如果 且 的个位数是 ,那么 不是回文数,直接返回
false; - 如果 的个位数不是 ,那么 可能是回文数,继续执行下面的步骤。
我们将 的后半部分反转,与前半部分进行比较,如果相等,那么 是回文数,否则 不是回文数。
举个例子,例如 ,我们可以将数字后半部分从 “21” 反转为 “12”,并将其与前半部分 “12” 进行比较,因为二者相等,我们得知数字 是回文。
让我们看看如何将后半部分反转。
对于数字 ,如果执行 ,我们将得到最后一位数字 ,要得到倒数第二位数字,我们可以先通过除以 将最后一位数字从 中移除,,再求出上一步结果除以 的余数,,就可以得到倒数第二位数字。
如果继续这个过程,我们将得到更多位数的反转数字。
通过将最后一位数字不断地累乘到取出数字的变量 上,我们可以得到以相反顺序的数字。
在代码实现上,我们可以反复“取出” 的最后一位数字,并将其“添加”到 的后面,循环直到 ,如果此时 ,或者 ,那么 就是回文数。
时间复杂度 ,其中 是 。对于每次迭代,我们会将输入除以 ,因此时间复杂度为 。空间复杂度 。
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0 or (x and x % 10 == 0):
return False
y = 0
while y < x:
y = y * 10 + x % 10
x //= 10
return x in (y, y // 10)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(log10(n)) because each step processes one digit, reducing the number by a factor of 10. Space complexity is O(1) since no additional data structures are used beyond simple integer variables. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Checks if you can handle numeric operations without string conversion.
- question_mark
Sees if you consider edge cases like negatives and trailing zeros.
- question_mark
Wants to test knowledge of integer overflow and efficient reversal.
常见陷阱
外企场景- error
Reversing the entire number can cause integer overflow.
- error
Forgetting to handle negative numbers or numbers ending in 0.
- error
Using string conversion instead of math-driven digit operations.
进阶变体
外企场景- arrow_right_alt
Check palindrome for a number represented as a linked list.
- arrow_right_alt
Determine if a number is a palindrome in a different base, e.g., binary.
- arrow_right_alt
Find the longest palindromic subsequence within the integer's digits.