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
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
①
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x>0:
t=1
else:
t=-1 #save the sign
a=[]
x = abs(x)
while x:
a.append(x%10)
x = x//10 #save every single number
b = sum(a[i]*(10**(-i+len(a)-1)) for i in range(len(a)))*t #calculate
if b>2**31-1 or b<-2**31:
return 0 #deal with the exceptions
else:
return b
Approach 1: Pop and Push Digits & Check before Overflow
Intuition
We can build up the reverse integer one digit at a time. While doing so, we can check beforehand whether or not appending another digit would cause overflow.
Algorithm
Reversing an integer can be done similarly to reversing a string.
We want to repeatedly "pop" the last digit off of x and "push" it to the back of the rev. In the end, rev will be the reverse of the x.
To "pop" and "push" digits without the help of some auxiliary stack/array, we can use math.
//pop operation:
pop = x %10;
x /=10;
//push operation:
temp = rev *10+ pop;
rev = temp;
However, this approach is dangerous, because the statement temp = rev⋅10+pop can cause overflow.
Luckily, it is easy to check beforehand whether or this statement would cause an overflow.
To explain, lets assume that rev is positive.
If temp =rev⋅10+pop causes overflow, then it must be that rev≥NTMAX/10
If rev>NTMAX/10, then temp =rev⋅10+pop is guaranteed to overflow.
If rev==NTMAX/10, then temp = rev⋅10+pop will overflow if and only if pop>7 for 2**31=2 147 483 648
Similar logic can be applied when rev is negative.
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
intmax = 2**31-1
intmin = -2**31
rev = 0
if x>0:
t = 1
else:
t = -1 #need to abstract the sign first, because of the x%10 operation for negative numbers in python is different from the common knowledge. for example, -123%10 = 7 but not -3
x = abs(x)
while x:
pop = x%10
x = x//10
if rev > intmax//10 or (rev == intmax//10 and pop>7):
return 0
if rev < intmin//10 or (rev == intmin//10 and pop<-8):
return 0
rev = rev*10+pop # compare to my method, it avoids calculating 10**i * a[i], simply just recursively multiply 10 to the previous result.
return rev*t
-123%10=7 but not -3
recursive calculation