class Solution {
public int reverse(int x) {
int ans=0;
while(x!=0){
int pop=x%10;
if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && pop > 7))
return 0;
if (ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE / 10 && pop < -8))
return 0;
ans=ans*10+pop;
x=x/10;
}
return ans;
}}
if (ans > Integer.MAX_VALUE / 10)
return 0;
if (ans < Integer.MIN_VALUE / 10 )
return 0;
这段代码是解决栈溢出,一般一处处理办法有两种,一种是try....catch,另一种则是数学计算来解决。
由于本题是字符串,用try....catch解决效率比较低。