23
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!

3
  • 3
    The largest 32-bit signed integer is (1 << 31) - 1, which is 2147483647. Commented Aug 6, 2017 at 4:58
  • Assuming you're checking for signed integers, you need abs(sum) > 2 ** 31 - 1 (or, even better, abs(sum) > (1 << 31) - 1) Commented Aug 6, 2017 at 5:03
  • 2
    This code is a lot more complicated than it needs to be. For instance, you can reverse a string in a single step, you don't need a for loop to do it. BTW, it's not a good idea to use sum as a variable name because that shadows the built-in sum function. It won't hurt anything here, though. Commented Aug 6, 2017 at 6:09

6 Answers 6

36

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

Sign up to request clarification or add additional context in comments.

6 Comments

I think down voter should provide justification why?
seems like someone upvoted my answer. But I still wish whoever downvoted it can give an explanation.
Yeah who downvoted? I selected your answer. Thanks for the explanation!
@OLIVER.KOO I understand reserving 1 bit as the sign bit, so it's not to the power of 32 but rather 31. But can you explain why is it "minus 1"? Why is it not (2**31)? Thanks!
I think the smallest 32-bit signed integer is - 2 ** 31
|
3

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

1 Comment

@ErikvonAsmuth ok fixed
1

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

Comments

1
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)

Comments

0

you can simply use:

if sum >= pow(2,31)-1:
     return 0

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.