反转整数(难度:简单)
题目描述
给定一个 32 位有符号整数,将整数中的数字进行反转.注意:
假设我们的环境只能存储 32 位有符号整数,其数值范围是 [-2^31, 2^31-1]。根据这个假设,如果反转后的整数溢出,则返回 0。
解题思路
方法:弹出和推入数字 & 溢出前进行检查思路
我们可以一次构建反转整数的一位数字。在这样做的时候,我们可以预先检查向原整数附加另一位数字是否会导致溢出。算法反转整数的方法可以与反转字符串进行类比。我们想重复“弹出” xxx 的最后一位数字,并将它“推入”到 temp的后面。最后,temp 将与 xxx 相反。要在没有辅助堆栈 / 数组的帮助下 “弹出” 和 “推入” 数字,我们可以使用数学方法。
//pop operation:
pop = x % 10;
x /= 10;
//push operation:
temp = temp * 10 + pop;
但是这种方法很危险,因为当 temp=temp⋅10+pop 时会导致溢出。幸运的是,检查这个语句是否会导致溢出很容易。
为了便于解释,我们假设 temp 是正数。
如果temp=temp⋅10+pop导致溢出那么一定有 temp≥INTMAX/10
如果 temp>INTMAX/10,那么 temp=temp⋅10+pop一定会溢出。
如果 temp==INTMAX/10,那么只要 pop>7,temp=temp⋅10+pop就会溢出。
当 temp为负时可以应用类似的逻辑。
class Solution {
public int reverse(int x) {
int temp=0;
while(x!=0){
int pop=x%10;
x/=10;
if(temp>Integer.MAX_VALUE/10||(temp==Integer.MAX_VALUE/10&&pop>7))
return 0;
if(temp<Integer.MAX_VALUE/10||(temp==Integer.MAX_VALUE/10&&pop<-8))
return 0;
temp=temp*10+pop;
}
return temp;
}
}