给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0
solution 1:
看作字符串,但实际上最后判断溢出那里是错的
class Solution:
def reverse(self, x: int) -> int:
if x<0:
sign = -1
else:
sign = 1
s = str(abs(x))
sr = s[::-1]
i = int(sr);
if i>2**31-1:
i = 0
elif i<-2**31:
i = 0
return sign*i
执行用时 : 64 ms, 在Reverse Integer的Python3提交中击败了93.25% 的用户
内存消耗 : 13.2 MB, 在Reverse Integer的Python3提交中击败了0.97% 的用户
solution 2 :
我们想重复“弹出” xx 的最后一位数字,并将它“推入”到 \text{rev}rev 的后面。最后,\text{rev}rev 将与 xx 相反。
要在没有辅助堆栈 / 数组的帮助下 “弹出” 和 “推入” 数字,我们可以使用数学方法。
//pop operation:
pop = x % 10;
x /= 10;
//push operation:
temp = rev * 10 + pop;
rev = temp;
但是,这种方法很危险,因为当 \text{temp} = \text{rev} \cdot 10 + \text{pop}temp=rev⋅10+pop 时会导致溢出。
幸运的是,事先检查这个语句是否会导致溢出很容易。
为了便于解释,我们假设 rev 是正数。
- 如果 temp=rev⋅10+pop 导致溢出,那么一定有rev≥INTMAX/10。
- 如果 rev>INTMAX/10,那么 temp=rev⋅10+pop 一定会溢出。
- 如果 rev==INTMAX/10,那么只要 pop>7,temp=rev⋅10+pop 就会溢出。
class Solution:
def reverse(self, x: int) -> int:
re = 0;
if x < 0:
a = -10
else:
a = 10
while (x):
temp = x % a
if re>214748364 or (re==214748364 and temp>7):
return 0
if re<-214748364 or (re==-214748364 and temp<-8):
return 0
re = temp + re*10
x = int(x / 10)
return re