题目:
"""
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
"""
法一:前后对称比较
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
string = str(x)
if len(string) == 1:
return True
l = len(string)
left = 0
right = l-1
while left < right :
if string[left] != string[right]:
return False
left += 1
right -= 1
return True
法二:正反字符串比较(全部)
class Solution:
def isPalindrome(self, x: int) -> bool:
s = str(x)
right = len(s)-1
result = ""
while right >= 0:
result += s[right]
right -= 1
if result == s:
return True
else:
return False
法三:正反字符串比较(全部_列表式推导)
class Solution:
def isPalindrome(self, x: int) -> bool:
s = str(x)
if s == s[::-1]:
return True
else:
return False
# 进一步优化
class Solution:
def isPalindrome(self, x: int) -> bool:
s = str(x)
return (s == s[::-1])
法四:正反字符串比较(取半)
class Solution:
def isPalindrome(self, x: int) -> bool:
s = str(x)
l = len(s)
half = l//2
return (s[:half]==s[-1:-half-1:-1])