【Leetcode刷题】:Python:9. 回文数

本文介绍了一种使用Python编程语言判断整数是否为回文数的方法。通过定义一个辅助函数来比较从中间向两端的字符是否相同,实现了对奇数和偶数长度字符串的有效处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

9. 回文数

代码

class Solution:
    def isPalindrome(self, x: int) -> bool:
        x = str(x)
        def help(i,j):
            while i >= 0 and j < len(x):
                if x[i] == x[j]:
                    i -= 1
                    j += 1
                else:
                    return False 
            if i == -1 and j == len(x):
                return True
            else:
                return False 
        if len(x)%2 == 1:
            return help(len(x)//2, len(x)//2)
        else:
            return help(len(x)//2-1, len(x)//2)