给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-number
例:
输入:x = 121
输出:true
输入:x = -121
输出:false
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
# 1 双指针。两个指针指向中心,然后像两端遍历。
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
s = str(x)
length = len(s)
left, right = 0, 0
if length & 1 == 1:
left, right = int(length//2), int(length//2)
else:
left, right = int(length/2-1), int(length/2)
while left >= 0 and right < length:
if left == 0 and right == length - 1:
if s[left] == s[right]:
return True
if s[left] != s[right]:
return False
left -= 1
right += 1
# 2 直接Python正反遍历即可:若正反遍历相同则代表是回文数
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
return x>-1 and str(x)[::-1]==str(x)
# 3 在不将整数转换成字符串的情况下解决。使用除余。
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
yu, y, x2 = 0, 0, x # 余数,翻转后的结果,当前x
while x2 != 0:
yu = x2%10 # 求余
y = y*10 + yu # 计算翻转
x2 = x2//10 # x右移一位
return y==x