问题描述:
给定32位有符号整数,整数的反向数字。
例1:
输入: 123
输出: 321
例2:
输入: -123
输出: -321
例3:
输入: 120
输出: 21
注意:
假设我们正在处理一个只能在32位有符号整数范围内存储整数的环境:[ - 2^31 2^31 - 1]。出于此问题的目的,假设当反向整数溢出时,函数返回0。
首先想到一个逻辑 ,用取余方式取得最后一位数pop,然后用res保存最后结果res = res * 10 + pop. 想到这里其次就是在获得执行这步之前判断结果是否溢出,
假设整数是正数,
如果res = res *10 + pop 导致Integer溢出,那么一定是 res>=Integer.MAX_VALUE;
(1)res>Integer.MAX_VALUE,一定溢出返回0
(2)res=Integer.MIN_VALUE,因为整数能存的最大整数是2147483647 所以判断下pop>7 会导致溢出。
反之, 负数同理。
代码实现
public int reverse(int x) {
int res = 0;
while(x!=0){
int pop = x%10;
x=x/10;
if(res>Integer.MAX_VALUE/10||(res==Integer.MAX_VALUE/10&&pop>7)){return 0;}
if(res<Integer.MIN_VALUE/10||(res==Integer.MIN_VALUE/10&&pop<-8)){return 0;}
res = res*10+pop;
}
return res;
}
接下来附一个更好的解决方案,用long来存储给定整数 只要在最后判断一次是否溢出整数就行。
public class Solution {
public int reverse(int x) {
long answer = 0;
while(x != 0) {
answer = 10 * answer + x % 10;
x /= 10;
}
return (answer > Integer.MAX_VALUE || answer < Integer.MIN_VALUE) ? 0 : (int) answer;
}
}