回答正确,但运行时错误为Reverse Integer LeetCod

2024-10-01 09:41:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我的LeetCode上的反向整数代码不被接受。你知道吗

我已经检查了我的程序是否能返回正确答案。你知道吗

class Solution:
    def reverse(self, x: int) -> int:
        check_num = str(x)
        flag = 0
        if(check_num[0] == '-'):
            check_num = check_num[1:]
            flag = 1

        elif (check_num[len(check_num)-1] == '0'):
            check_num = check_num[:len(check_num)-1]

        #print(check_num)

        #reverse
        time = len(check_num)
        storage = [0] * time 
        for i in range(len(check_num)):
            num = len(check_num)-i-1
            storage[i] = check_num[num]
            #print(storage[i])

        if(flag == 1):
            storage.insert(0, '-')

        #turn to string
        oneLinerString=""
        for x in storage:
            oneLinerString += x

        ans = int(oneLinerString)

        return oneLinerString

def main():
    import sys
    import io
    def readlines():
        for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
            yield line.strip('\n')

    lines = readlines()
    while True:
        try:
            line = next(lines)
            x = int(line);

            ret = Solution().reverse(x)

            out = str(ret);
            print(out)
        except StopIteration:
            break

if __name__ == '__main__':
    main()

对于一个输入情况,我的程序返回正确的输出。你知道吗

Your input
123
Output
321
Expected
321

但是有错误,我的代码不被接受。 有什么问题?我应该如何修复当前的代码?你知道吗

Finished in N/A
ValueError: invalid literal for int() with base 10: ''
Line 30 in reverse (Solution.py)
Line 47 in main (Solution.py)
Line 55 in <module> (Solution.py)

Tags: 代码inforlenmaindefcheckline
2条回答

尝试使用python发挥其优势:

def solve():
    n = input()
    l = list(map(int,str(n)))
    l = l[::-1]

    #removing leading zeros
    i = 0
    while l[i] == 0:
        i+=1
    l = l[i:]
    n = ('').join(str(x) for x in l)
    return int(n)

if __name__ == "__main__":
    print (solve())

对于0的输入,您的代码会将输入转换为空字符串,原因是:

elif (check_num[len(check_num)-1] == '0'):
            check_num = check_num[:len(check_num)-1]

您应该删除此elif分支,并让您的最终整数转换处理倒数的前导零:

ans = int(oneLinerString)  # removes leading zeros in the reversed string

您还需要注意当反向数超出32位有符号整数表示的范围时返回0的条件。因此,可以添加最终检查:

if not -2**31 <= ans <= 2**31 - 1:
    return 0

对示例代码进行最小的更改,一个可行的解决方案是:

class Solution:
    def reverse(self, x: int) -> int:
        check_num = str(x)
        flag = 0
        if(check_num[0] == '-'):
            check_num = check_num[1:]
            flag = 1

        #print(check_num)

        #reverse
        time = len(check_num)
        storage = [0] * time 
        for i in range(len(check_num)):
            num = len(check_num)-i-1
            storage[i] = check_num[num]
            #print(storage[i])

        if(flag == 1):
            storage.insert(0, '-')

        #turn to string
        oneLinerString=""
        for x in storage:
            oneLinerString += x

        ans = int(oneLinerString)  # removes leading zeros in the reversed string

        if not -2**31 <= ans <= 2**31 - 1:
            return 0

        return ans

相关问题 更多 >