checking integer overflow in python

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

    I guess some thing light weight like below could perhaps achieve the same logic, For someone else looking , the main overflow check after reversed 32 bit int is

    if(abs(n) > (2 ** 31 - 1)):
                        return 0    
    

    Full code below

    def reverse(self, x):
    
                neg = False
                if x < 0:
                    neg = True
                    x = x * -1
    
                s = str(x)[::-1]
                n = int(s)
                if neg:
                    n = n*-1
                if(abs(n) > (2 ** 31 - 1)):
                    return 0
                return n
    

提交回复
热议问题