整数反转
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
解答如下:
public static int fanzhuan1(int x) {
int temp = 0;
while (x != 0) {
// 每次取尾数
int pop = x % 10;
// 去尾数
x /= 10;
/**
* 整除得到的数不精确,因此还是存在越界的可能,查看源码可知
*
* @Native public static final int MAX_VALUE = 0x7fffffff;
*
* @Native public static final int MIN_VALUE = 0x80000000;
**/
if (temp > Integer.MAX_VALUE / 10 || temp == Integer.MAX_VALUE / 10 && pop > 7)
return 0;
if (temp < Integer.MIN_VALUE / 10 || temp == Integer.MIN_VALUE / 10 && pop < -8)
return 0;
// 反转
temp = temp * 10 + pop;
}
return temp;
}
原题链接:整数反转