在进行这道题目时,想的比较简单,没有想到溢出的问题,Integer是有边界的,需要考虑溢出的问题,如果结果,那么返回值为0
对于一个整数可以考虑使用/10以及%10的取余和取整来实现数字的反转
复习小知识点:/是取余 %是取整
对于溢出的问题,我走了个捷径,可以使用如下方法实现
public class Solution {
public int reverse(int x) {
long result = 0;
long z = 0;
while(x != 0){
z = x % 10;
x = x/10;
result = result*10 + z;
if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE ){
return 0;
}
}
return (int)result;
}
}
当然,如果要是研究的话还是使用下面的代码,需要考虑一下
public int reverse(int x)
{
int result = 0;
while (x != 0)
{
int tail = x % 10;
int newResult = result * 10 + tail;
if ((newResult - tail) / 10 != result)
{ return 0; }
result = newResult;
x = x / 10;
}
return result;
}
上述代码并非原创,可以拿来思考一下