将int类型的数字进行反转,因为是int类型,所以要考虑溢出的问题
分析
int 类型的数,最大位数为10,也就是每次拿到最后一个数,拼接到新的数,最多十次,就可以得到一个int数反转后的数
反转前如果该数字小于10,就不用反转
反转后溢出就返回0
public static int reverse(int x) {
//如果和10相除为0直接返回
if (x / 10 == 0){
return x;
}
long result = 0;
for (int i = 0 ; i < 10 ; i++ ){
//每循环一次将最终值向后移动一位,在加上传入数的最后一位
result = result*10 + x%10;
if (result < Integer.MIN_VALUE || result > Integer.MAX_VALUE){
return 0;
}
//每进行一次反转数就要去掉最后一位
x = x / 10;
if (x == 0){
//说明已经为最后一位,跳出
break;
}
}
return new Long(result).intValue();
}