判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数
- 双指针法: 设置指针
l
和r
分别指向str(x)
的首尾,然后依次比较:- 如果当前字符相同,则更新指针
- 如果当前字符不同,则直接返回False
另外如果x
为负数,直接返回False;如果x是小于10的正数,直接返回True。
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0: return False
if x < 10: return True
x = str(x)
l, r = 0, len(x) - 1
while l <= r:
if x[l] != x[r]:
return False
l += 1
r -= 1
return True
- 取余法:通过取余操作得到x反转后的形式,然后判断它和x是否相同即可。
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0: return False
if x < 10: return True
t = x
r = []
while t :
r.append(str(t % 10))
t = t // 10
return ''.join(r) == str(x)
或者直接比较反转后的数即可
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0: return False
if x < 10: return True
t = x
ans = 0
while t:
ans = ans * 10 + t % 10
t = t // 10
return ans == x