# Python solution with detailed explanation

• Solution

Algorithm and Special Conditions

• Integer means negative numbers, overflow and underflow, and handling 0
• What if integer last digit is 0? Example 10, 100, 1000. Algorithm must take care of this
• Make sure you convert to positive number and record the sign
• Take an example: reverse 123
• ret = 0
• ret = ret * 10 + x%10
• x = x/10
• Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows.
• Test for overflow: Do not let x drop below 10. Test if ret > max_32//10 or (ret == max_32//10 and x >7)
``````class Solution:
# @return an integer
def reverse(self, x):
ret, max_32 = 0, 2**31-1
neg, x = True if x<0 else False, x*-1 if x<0 else x
while x >= 10:
ret, x = ret*10 + x%10, x//10
if (ret > max_32//10) or (ret == max_32//10 and x >7):
return 0
else:
ret = ret*10 + x%10
return ret*-1 if neg else ret
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.