我检查数字是否为回文的代码出错

问题描述 投票:0回答:1

这是我的代码,用于检查数字是否是回文。

class Solution(object):
    def isPalindrome(self, x):
        string = str(x)
        idx = 0
        # if the number is even; 
        if (x % 2) == 0:
            for i in range (1, len(string)/2 + 1):
                if string[i - 1] == string[len(string) - i]:
                    idx += 1 
            if idx == len(string)/2: 
                return True
        #if the number is odd: 
        else: 
            if len(string) > 2: 
                for i in range(1, (len(string)-1)/2 + 1):
                    if string[i - 1] == string[len(string) - i]:
                        idx += 1
                if idx == (len(string)-1)/2:
                    return True
            elif len(string) == 2: 
                if string[0] == string[1]: 
                    return True
            else: 
                return True

但是,为什么当 x = 1000030001 时我的代码不起作用?我的程序认为 1000030001 是一个回文。谁能告诉我我的代码哪里不正确?

我已经尝试手动插入每个值进行调试,它显示它将返回 False,即使当我运行程序时它返回 True。

python string list for-loop palindrome
1个回答
0
投票

与代码有关的问题是您正在检查数字是否为偶数,而不是该数字的长度是偶数还是奇数。

© www.soinside.com 2019 - 2024. All rights reserved.