using Java,整数溢出问题
题目
Given a 32-bit signed integer, reverse digits of an integer.
难度
easy(主要问题在如何解决整数溢出)
思路
- 使用%10获得最后一位re的值,当前值x/10
- 使用当前ans*10+re获得当前翻转值
- 当当前值x==0时停止循环
- 解决溢出问题,考虑ans=ans*10+re 这步可能导致溢出,根据这个式子做出是否溢出的判断,如果ans是正:
情况1:ans>Integer.MAX_VALUE/10
情况2: ans==Integer.MAX_VALUE/10&&re>Integer.MAX_VALUE%10
同理可得负数的情况
代码
class Solution {
public int reverse(int x) {
int re,ans=0;
int maxlast=Integer.MAX_VALUE%10;//最大正整数的最后一位
int minlast=Integer.MIN_VALUE%10;//最小负整数的最后一位
do{
re=x%10;
x/=10;
if(ans>Integer.MAX_VALUE/10||(ans==Integer.MAX_VALUE/10&&re>maxlast)){
return 0;
}
if(ans<Integer.MIN_VALUE/10||(ans==Integer.MIN_VALUE/10&&re<minlast)){
return 0;
}
ans=ans*10+re;
}while(x!=0);
return ans;
}
}
注意点
- Integer.MAX_VALUE/10,因为整数除法,会舍去MAX_VALUE的最后一位,所以在判断溢出的时候,还要考虑re的情况