9 - Palindrome Number 难度:Easy| 简单 相关知识点: Math 题目链接:https://leetcode.com/problems/palindrome-number/description/ 数学方法 Solution 1: 通过反转一半的数字来减少计算次数 class Solution: def isPalindrome(self, x: int) -> bool: if x < 0 or (x % 10 == 0 and x != 0): return False reversed_half = 0 while x > reversed_half: reversed_half = reversed_half * 10 + x % 10 x //= 10 # 处理数字位数为奇数的情况 return x == reversed_half or x == reversed_half // 10 Solution 2:取整数反转后的值进行比较 def isPalindrome(x): if x < 0: return False original = x reversed_x = 0 while x != 0: reversed_x = reversed_x * 10 + x % 10 x //= 10 return original == reversed_x 字符串 Solution 3: 转成字符串比较 def isPalindrome(x): return str(x) == str(x)[::-1] Solution 4:将整数转成数组进行比较 class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False str_x = str(x) left, right = 0, len(str_x) - 1 while left < right: if str_x[left] != str_x[right]: return False left += 1 right -= 1 return True