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

代码在VS运行正常,LeetCode提交报'int' object has no attribute '__getitem__'错误

解决LeetCode中'int' object has no attribute 'getitem'错误

问题核心是输入类型不匹配:

  • 本地用input()获取的是字符串类型,能直接用[::-1]切片反转;
  • 但LeetCode的题目(比如回文数题)是直接传入整数类型参数,整数没有切片(__getitem__)方法,所以第2行触发报错。

解决方法1:转字符串处理(最简单直接)

把传入的整数转成字符串,再执行反转比较:

def isPalindrome(x: int) -> bool:
    s = str(x)
    return s == s[::-1]

匹配你原代码结构的写法:

# 对应LeetCode输入场景,x为整数
s = str(x)
reverseuserinput = s[::-1]

if s == reverseuserinput:
    print("true")
else:
    print("false")

解决方法2:数学方法反转数字(适合禁止转字符串的场景)

如果题目限制不能用字符串操作,可通过数学运算反转数字:

def isPalindrome(x: int) -> bool:
    # 负数直接排除回文数可能
    if x < 0:
        return False
    original_num = x
    reversed_num = 0
    while x > 0:
        # 取最后一位数字累加到反转数中
        reversed_num = reversed_num * 10 + x % 10
        # 移除原数的最后一位
        x = x // 10
    return original_num == reversed_num

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:37:14