给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
class Solution {
public int reverse(int x) {
int[] a=new int[20];
int num=0,n=x;;
int newx=0;
int flag;
if(x>=0) flag=1;
else flag=0;
while(n!=0){
a[num]=n%10;
n=n/10;
num++;
}
for(int i=0;i<num;i++){
if(flag==1){
if (newx>Integer.MAX_VALUE/10 || (newx == Integer.MAX_VALUE / 10 && a[i]> 7))
return 0;
}
if(flag==0){
if (newx<Integer.MIN_VALUE/10 || (newx == Integer.MIN_VALUE / 10 && 0-a[i] < -8))
return 0;
}
newx=newx*10+a[i];
}
return newx;
}
}
2^31-1=2147483647
-2^31=-2147483648
为了便于解释,我们假设是正数。
- 如果newx = newx⋅10+a[i] 导致溢出,那么一定有newx ≥ Integer.MAX_VALUE/10。
- 如果 newx > Integer.MAX_VALUE/10,那么newx = newx⋅10+a[i] 一定会溢出。
- 如果 newx = Integer.MAX_VALUE/10,那么只要a[i] > 7,newx = newx⋅10+a[i] 就会溢出。