1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| class Solution: """ 类似双指针 左右以此对比 直到右指针索引比左指针小 """ def isPalindrome1(self, x: int) -> bool: s = str(x) print(s) i , j = 0, len(s) - 1 while i <= j: if s[i] != s[j]: return False i += 1 j -= 1 return True
""" Python中直接反转字符串 """ def isPalindrome2(self, x: int) -> bool: return str(x) == str(x)[::-1]
""" 纯数学解法 1.掌握遍历 int 类型,即先x mod 10,再x / 10,直至 x = 0 2.反转整数,rev初始等于0,rev = rev*10 + x mod 10 """ def isPalindrome3(self, x: int) -> bool: if x < 0: return False elif x < 10: return True else: if x % 10 == 0: return False else: rev = 0 while x != 0: rev = rev * 10 + x % 10 x //= 10 if rev == x // 10: return True if rev == x: return True return False
""" 对 isPalindrome3 的优化 """ def isPalindrome4(self, x: int) -> bool: if x < 0 or x > 0 and x % 10 == 0: return False rev = 0 while rev < x // 10: rev = rev * 10 + x % 10 x //= 10 return rev == x or rev == x // 10
|