9. 回文数

Easy

思路

首先理解什么是回文,回文的意思是,反过来读和正着读是一样的,那我们按照这个思路写出代码,AC!

代码

python3

class Solution:
    def isPalindrome(self, x: int) -> bool:
      return str(x) == str(x)[::-1]

题目要求不转成字符串来解题,那我们需要用数学的方法来进行操作

更新思路

12 % 10 = 2
1 % 10 = 1
2 * 10 + 1 = 21

代码

python3

class Solution:
    def isPalindrome(self, x: int) -> bool:
      if x < 0 or (x%10 == 0 and x != 0):
        return False
      res = 0
      while x > res:
        res = res * 10 + x % 10
        x //= 10
      return x == res or x == res//10