问题描述
思路与代码
本题较为简单,关键在于 Follow up 中的发问,即能否不转为字符串来求解。
转为字符串的方法
先考虑最常规的思路,即转为字符串,然后使用双指针法,头尾指针相互逼近,按位判断。
代码如下:
class Solution:
def isPalindrome(self, x: int) -> bool:
# negative number not palindrome
if x < 0:
return False
list_x = list(str(x)) # convert to string
i, j = 0, len(list_x) - 1
while i < j: # 2-pointer method
if list_x[i] != list_x[j]:
return False
i += 1
j -= 1
return True
运行效果:
不转为字符串的方法
不转为字符串的方法比较巧妙,是通过求余的方式将原数字反转,然后将反转后的数字与原数字进行比较,如相等,则为回文数,否则,不是回文数。
代码如下:
class Solution:
def isPalindrome(self, x: int) -> bool:
# special cases: negative; end up with 0
if x < 0 or (x and not x % 10):
return False
rev = 0
x_ = x
while x > rev:
rev = rev * 10 + x_ % 10
x_ = int(x_ / 10)
return rev == x
运行效果: