Given a 32-bit signed integer, reverse digits of an integer.
def reverse(self, x): y = str(x) #checks the number if negative it removes the - sign if y == '-': 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))
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.