简体   繁体   English

LeetCode 反向整数(ValueError:int() 的无效文字,基数为 10: '' )

[英]LeetCode Reverse Integer (ValueError: invalid literal for int() with base 10: '' )

Given a signed 32-bit integer x, return x with its digits reversed.给定一个有符号的 32 位整数 x,返回其数字反转的 x。 If reversing x causes the value to go outside the signed 32-bit integer range [-2**31, 2**31 - 1], then return 0.如果反转 x 导致值超出有符号的 32 位整数范围 [-2**31, 2**31 - 1],则返回 0。

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).假设环境不允许您存储 64 位整数(有符号或无符号)。

This is my submission这是我的提交

class Solution(object):
def reverse(self, x):
    sp= str(abs(x))[::-1].lstrip("0")
    ans= int(sp)
    
    if x > 0 :
        return ans
    else: 
        return -1*ans

The int() method should allow me to pass a string value ("12"), but it returns an error saying that it's an invalid literal for int(). int() 方法应该允许我传递一个字符串值(“12”),但它返回一个错误,指出它是 int() 的无效文字。

The variable sp in line 3 is a str not a float , so I have no idea why it doesn't run on the leetcode submission page, as it runs ok on VSCode.第 3 行中的变量spstr 而不是 float ,所以我不知道为什么它不在 leetcode 提交页面上运行,因为它在 VSCode 上运行正常。

Is there any grading guideline that I missed?有没有我错过的评分指南?

And, this is the Value Error I'm getting而且,这是我得到的价值错误

在此处输入图片说明

There are two problems with the original code: (1) It won't handle zero, and (2) The range checks in the problem description are missing.原始代码有两个问题:(1)它不会处理零,以及(2)问题描述中的范围检查缺失。

For zero, the string representation is "0" .对于零,字符串表示为"0" But after calling lstrip("0") , it will be the empty string, which int won't accept.但是在调用lstrip("0") ,它将是空字符串, int不会接受。 This can be fixed by making a special-case check for zero.这可以通过对零进行特殊情况检查来解决。 An even simpler fix (suggested by Mark) is not to strip the leading zeros.更简单的解决方法(由 Mark 建议)是不去除前导零。

For the range checks, just add a check to return zero if the value is out of range.对于范围检查,如果值超出范围,只需添加一个检查以返回零。

Here's an updated version with both fixes in place.这是一个更新版本,其中包含两个修复程序。 Note this this version omits the strip("0") call, which fixes the zero case:请注意,此版本省略了strip("0")调用,它修复了零情况:

class Solution(object):
    def reverse(self, x):
        sp = str(abs(x))[::-1]
        ans = int(sp)

        if x < 0:
            ans = -ans

        if ans < -2**31 or ans > 2**31 - 1:
            return 0

        return ans

This should handle all of the test cases correctly.这应该正确处理所有测试用例。

Error said you try to int() a None string or letter not number so check variable sp before int()错误说你尝试 int() 一个 None 字符串或字母不是数字所以在int()之前检查变量sp

Try this试试这个

class Solution(object):
def reverse(self, x):
    sp= str(abs(x))[::-1].lstrip("0")
    if not sp:
        return 0
    ans= int(sp)
    
    if x > 0 :
        return ans
    else: 
        return -1*ans

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM