刚开始想法是字符处理,代码如下:
class Solution {
public int reverse(int x) {
if(x == 0) return x;
String str = "";
int value;
if(x<0){
str = "-" + str;
x = -x;
}
while(x>0){
int mou = x%10;
String str1 = String.valueOf(mou);
str = str + str1;
x=x/10;
}
long value1 = Integer.parseInt(str);
if(value1 < Integer.MIN_VALUE || value1 > Integer.MAX_VALUE){
return 0;
}
return Integer.parseInt(str);
}
}
会报错,报错如下:
即在str = “9646324351”报错。
原因出在 long value1 = Integer.parseInt(str);这上面,这是string 转换为 int类型的,当str转换的数大于int的最大值时, Integer.parseInt(str)就不适用了。
修改代码,用数值。
class Solution {
public int reverse(int x) {
int res = 0;
while(x!=0){
int tmp = x%10;
//
if (res>214748364 || (res==214748364 && tmp>7)) {
return 0;
}
if (res<-214748364 || (res==-214748364 && tmp<-8)) {
return 0;
}
res = res*10 + tmp;
x /= 10;
}
return res;
}
}
在运算中间加上判断条件 。