需要注意的点
判断整数溢出
if (count>Integer.MAX_VALUE / 10 || (count214748364 && z>7)) {
return 0;
}
if (count<-214748364 || (count-214748364 && z<-8)) {
return 0;
}
数据范围为-2147483648 到2147483647[-231~231-1]
注意,要先提前判断整数是否会溢出,在确定了整数不会溢出后再把最后一位加到整数上
count=count10;
count=count+z;
小细节,先count10再+z,这样判断溢出就不会出错。
class Solution {
public static int reverse(int x) {
//23 23%10=3 now= 23/10 将取余的数加到总数,count=3,当now不等于0时,count*10,
int now,count=0;
while (x!=0)
{
int z=x%10;
if (count>214748364 || (count==214748364 && z>7)) {
return 0;
}
if (count<-214748364 || (count==-214748364 && z<-8)) {
return 0;
}
count=count*10;
count=count+z;
x=x/10;
}
return count ;
}
}