checking integer overflow in python

Viewed 30757
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

This is a leetcode problem that asks us to reverse an integer. I know it's a dirty code but it still works but it does not return 0 when the reversed integer overflows. I tried to check that on the line

        if(abs(sum) > 2 ** 32):
            return 0

but one of the test cases gives me:

Input: 1563847412

Output: 2147483651

Expected: 0

First, I am not sure why this overflows, and I am not sure how to fix this.

Thanks!

6 Answers

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
class Solution:
    def reverse(self, x: int) -> int:

        split = [i for i in str(x)]
        split = split[::-1]
        final = ''

        
        if split[-1]=='-':
            final += '-'
            
            for i in split[0:-1]:
                print(i)
                final+=i
        else:
            
            for i in split[0:]:
                final+=i
                
        final = int(final)
        
        if(abs(final) > (2 ** 31 - 1)):
                return 0
                
        return(final)

you can simply use:

if sum >= pow(2,31)-1:
     return 0
if sum > ((1 << 31) - 1):
    return 0
else:
    if negative == True:
      sum = -sum
      return sum
Related