You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

回文数判断代码错误排查:为何1000030001被误判为回文?

问题分析:回文数判断代码错误原因

问题描述

我编写了用于判断数字是否为回文数的代码:

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时,程序错误返回True,但实际该数不是回文数(手动验证应为False),请问代码哪里有问题?

核心错误

你的代码犯了根本性逻辑错误:用原数字的奇偶性来决定字符串长度的处理逻辑,但数字的奇偶性和其字符串长度的奇偶性完全无关!

以输入1000030001为例:

  • 数字本身是奇数(末尾为1),代码进入else分支(奇数数字的处理逻辑)
  • 但它的字符串长度是10(偶数),此时代码按照奇数长度逻辑处理,仅比较了前4对对称字符(索引0&9、1&8、2&7、3&6),完全跳过了中间的第4位(索引4,字符0)和第5位(索引5,字符3)的比较,因此错误判断为回文数。

修正方案

正确逻辑应该是根据字符串长度的奇偶性处理,而非原数字的奇偶性。同时可以简化冗余逻辑:

方案1:直接比较字符串与反转字符串(最简洁)

class Solution(object):
    def isPalindrome(self, x):
        s = str(x)
        return s == s[::-1]

方案2:双指针循环比较(保留原思路的优化版)

class Solution(object):
    def isPalindrome(self, x):
        string = str(x)
        n = len(string)
        for i in range(n // 2):
            if string[i] != string[n - 1 - i]:
                return False
        return True

该方案用双指针逐个比对对称位置字符,只要有一对不相等就直接返回False,全部匹配则返回True,逻辑清晰且高效。

内容的提问来源于stack exchange,提问作者Coda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 03:47:46