方法:
第5题的子问题,又和第7题的解题方法一样,做题顺序应该是9 -> 5, 7
1 用数字逆序处理,第7题方法
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
old_x = x
reverse_x = 0
while x:
remainder = x % 10
reverse_x = reverse_x * 10 + remainder
x //= 10
return reverse_x == old_x
2 第5题子问题解法
class Solution:
def isPalindrome(self, x: int) -> bool:
s = str(x)
def helper(l, r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
if l < 0 and r >= len(s):
return True
return False
mid = (len(s) - 1) // 2
if len(s) % 2 == 1:
return helper(mid, mid)
return helper(mid, mid + 1)
如果有要求:
Follow up: Could you solve it without converting the integer to a string?
那么用方法一