检查python中的整数溢出

Duk*_*s17 12 python

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        negative = False
        if(x < 0):
            x = x * -1
            negative = True
        else:
            x = x
        sum = 0
        dig = 1
        strX = str(x)
        lst = list(strX)
        for i in lst:
            sum += int(i) * dig
            dig *= 10

        if(abs(sum) > 2 ** 32):
            return 0
        elif(negative == True):
            return sum * -1
        else:
            return sum
Run Code Online (Sandbox Code Playgroud)

这是一个leetcode问题,要求我们反转一个整数.我知道它是一个脏代码,但它仍然有效,但当反向整数溢出时它不会返回0.我试着检查一下

        if(abs(sum) > 2 ** 32):
            return 0
Run Code Online (Sandbox Code Playgroud)

但其中一个测试用例给了我:

Input: 1563847412
Run Code Online (Sandbox Code Playgroud)
Output: 2147483651
Run Code Online (Sandbox Code Playgroud)
Expected: 0
Run Code Online (Sandbox Code Playgroud)

首先,我不确定为什么会溢出,我不知道如何解决这个问题.

谢谢!

OLI*_*KOO 19

更改if(abs(sum) > 2 ** 32):if(abs(sum) > (2 ** 31 - 1)):abs(sum) > (1 << 31) - 1):最大的32位有符号整数实际上不是2 ^ 32但是(2 ^(31)) - 1).因为我们需要一位保留作为符号位.

在这里阅读它为什么数字2,147,483,647(或十六进制7FFF,FFFF)是32位有符号二进制整数的最大正值