checking integer overflow in python

后端 未结 6 634
故里飘歌
故里飘歌 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:23

    The largest 32-bit signed integer is (1 << 31) - 1 which is (2**31)-1 but not (2**32).

    Try This way :

    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) > ((1 << 31) - 1)): #use (1 << 31) - 1) instead of 2 ** 32
          return 0
        elif (negative == True):
          return sum * -1
        else:
          return sum
    
    if __name__ == '__main__':
        x = 1563847412
        sol = Solution().reverse(x)
        print(sol)
    

    Output :

    0
    

提交回复
热议问题