ReverseNum

reverseNum

Problem

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123

Output:  321

Example 2:

Input: -123

Output: -321

Example 3:

Input: 120

Output: 21

Code

def reverse(self, x):

    y = str(x)

    #checks the number if negative it removes the - sign

    if y[0] == '-':

        negative = True

        y = y[1:]

        else:

            negative = False

    #reverses the string [begin:end:step]

    x = y[::-1]

    #if it is negative reverse the sign

    if negative:

        x =  '-' + x

    #checks to make sure it doesnt overflow the 32bit

    if(abs(int(x)) > (2 ** 31 - 1)):

        x = 0

    return(int(x))

Developer’s  Notes

There are a couple of ways to tackle this problem. Here I decide to take advantage of Python’s ability of string manipulation.

I converted the number to a string, checked for a negative, then reversed the string adding the negative if necessary.  At the end of the script, I made sure it was less than the 32bit requirement by a size comparison and returned the result.