为了防止Integer overflow。利用long存储数据
public int reverse(int x) {
ArrayList <Integer> list = new ArrayList();while( x != 0){
list.add(x % 10);
x /= 10;
}
long result =0;
int ten = 1;
for(int i = list.size() - 1;i >= 0;i--){
result += ten * list.get(i);
ten *= 10;
System.out.println(result);
if(result > Integer.MAX_VALUE|| result < Integer.MIN_VALUE)
return 0;
}
return (int) (long) result;
}
但是当数值超越了int的最大值的时候,并没有返回0.
正确的做法是
result += (long)ten * list.get(i);
将其强制转换成long