<div>
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
- For example,
121is a palindrome while123is not.
Example 1:
<pre>Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left. </pre>
Example 2:
<pre>Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. </pre>
Example 3:
<pre>Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. </pre>
Constraints:
-2<sup>31</sup> <= x <= 2<sup>31</sup> - 1
Follow up: Could you solve it without converting the integer to a string?</div>
题目大意:
判断是否回文数字
解题思路:
N/A
解题步骤:
N/A
注意事项:
Python代码:
1
2def isPalindrome(self, x: int) -> bool:
return str(x) == str(x)[::-1]
算法分析:
时间复杂度为O(n),空间复杂度O(n)
算法II解题思路:
Follow-up 不能用str,就求它的reversed数
注意事项:
- x是用于计算过程,所以不断变化,最后一行不能用它来与reversed的结果比较
Python代码:
1
2
3
4
5
6
7
8def isPalindrome2(self, x: int) -> bool:
if x < 0:
return False
rev, original = 0, x
while x > 0:
rev = rev * 10 + x % 10 # 121
x = x // 10 # 1
return rev == original
算法分析:
时间复杂度为O(n),空间复杂度O(1)


