Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
public class ReverseInteger {
public static void main(String[] args) {
System.out.println(reverse(-123));
}
public static int reverse(int x) {
int digit = 0;
int carry = 0;
while (x != 0) {
//1.得到原数的最后一位
carry = x % 10;
//2.判断一手原数是否越界
if (digit > Integer.MAX_VALUE / 10 || digit < Integer.MIN_VALUE / 10){
return 0;
}
//3.新的数乘以10再加上刚才得到的最后一位
digit = digit * 10 + carry;
//4.原数去掉最后一位
x /= 10;
}
return digit;
}
}