checking integer overflow in python

后端 未结 6 632
故里飘歌
故里飘歌 2021-02-05 08:01
class Solution(object):
    def reverse(self, x):
        \"\"\"
        :type x: int
        :rtype: int
        \"\"\"
        negative = False
        if(x < 0):
          


        
6条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-05 08:16

    change if(abs(sum) > 2 ** 32): to if(abs(sum) > (2 ** 31 - 1)): or abs(sum) > (1 << 31) - 1): The largest 32 bit signed interger is actually not 2^32 but (2 ^ (31)) -1). because we need one bit reserve as the sign bit.

    Read about it here of why The number 2,147,483,647 (or hexadecimal 7FFF,FFFF) is the maximum positive value for a 32-bit signed binary integer

提交回复
热议问题