2022-01-30 leetcode 9\. 回文数

9. 回文数

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false

回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。

image.png

我的题解

使用整除,得到反向的整数,判断二者是否相等,相等则为回文数,否则不是

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False

        nums = []
        x_back = x
        while x >= 10:
            nums.append(x % 10)
            x //= 10
        nums.append(x)
        new_x = 0
        length = len(nums)
        for i in range(length):
            new_x += nums[i] * 10 ** (length - 1 - i)           
  
        return new_x == x_back

官方题解

image.png

image.png

image.png

优化思路:

  1. 反转一半数字即可达成判断
  2. 末尾为0的非0数字,一定不是回文数
class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0 or (x % 10 == 0 and x != 0):
            return False
        revertedNumber = 0
        while x > revertedNumber:
            revertedNumber = revertedNumber * 10 + x % 10
            x //= 10
        return x == revertedNumber or x == revertedNumber // 10

你可能感兴趣的:(2022-01-30 leetcode 9\. 回文数)