Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer (within the 32-bit signed integer range).Return 0 if reversed integer overflows. Problem from LeetCode


In [35]:
# Input
x = -123347898

In [36]:
# Method 1
def reverse1(x):
    """
    :type x: int
    :rtype: int
    """
    if 0 <= x <= 2**31:
        x = int(str(abs(x))[::-1])
    elif -2**31 <= x <= 0:
        x = -(int(str(abs(x))[::-1]))
    return 0 if x > 2**31 or x < -2**31 else x

In [37]:
# Method 2
def reverse2(x):
    """
    :type x: int
    :rtype: int
    """
    sign = (x > 0) - (x < 0)
    reverse = int(str(abs(x))[::-1])
    return reverse*sign if reverse < 2**31 else 0

In [38]:
# Output
reverse1(x), reverse2(x)


Out[38]:
(-898743321, -898743321)