回文数字

last modify

回文数字_牛客题霸_牛客网

问题简述

在不使用额外的内存空间的条件下判断一个整数是否是回文。
回文指逆序和正序完全相同。

思路1:模拟

  • 通过数学计算,不断获取首位和末位,比较;

  • 注意使用 log10 计算数字的位数时,x 不能为 0;

Python
class Solution:
    def isPalindrome(self , x: int) -> bool:
        # write code here
        import math
        
        # 负数不符合
        if x < 0: return False
        
        # 获取 x 的位数
        #     +0.1 防止 x 为 0,因为 x 为整数,所以不会影响结果
        n = math.ceil(math.log10(x + 0.1))
        
        # n > 0 也可以,大于 1 更好,如果最后只剩一个数字,必然符合
        while n > 1:  
            l = x // (10 ** (n - 1))
            r = x % 10
            if l != r:
                return False
            x -= l * 10 ** (n - 1)  # 移去首位
            x //= 10  # 移去末位
            n -= 2  # 位数减 2
        
        return True

思路2:反转数字

Python
class Solution:
    def isPalindrome(self , x: int) -> bool:
        if x < 0: return False
        
        ret = 0
        tmp = x
        while tmp:
            c = tmp % 10
            ret = ret * 10 + c
            tmp //= 10
        
        return ret == x

Last updated