整數反轉
給出一個 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;
}
原題鏈接:整數反轉