回文数检测程序遇无效字面量错误:VS Code正常但LeetCode报错
整数回文数检测程序LeetCode提交报错解决方案
问题根源
你的代码在处理负数输入时会触发无效整数字面量错误:当输入为负数(如-121),转成字符串后是"-121",反转得到"121-",此时用int()转换该字符串会因负号位置非法报错。此外原代码仅处理了相等的情况返回True,未覆盖不相等时返回False的逻辑,存在漏洞。
修正后的代码方案
方案1:先排除负数,完善逻辑
class Solution: def isPalindrome(self, x: int) -> bool: # 负数不可能是回文数,直接返回False if x < 0: return False s = str(x) rev = s[::-1] newint = int(rev) return newint == x
方案2:直接对比字符串(更简洁高效)
无需将反转后的字符串转回整数,直接对比原字符串和反转字符串即可,避免转换报错:
class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False s = str(x) return s == s[::-1]
内容的提问来源于stack exchange,提问作者Saul
相关产品推荐
相关产品推荐

