问题:给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31, 2^31 − 1]。
如何将整数中的每位数取出呢?
进行循环模运算,判断条件为整数x>0。但由于题目条件为有符号整数,故将判断条件修改为x!=0。
由于题目提出数值范围为 [−2^31, 2^31 − 1],所以需要判断反转后的ans是否溢出。
ans的溢出条件为ans > Integer.MAX_VALUE或ans < Integer.MIN_VALUE。
代码:
public int reverse(int x) {
int ans = 0; // 用于放置反转后的数
while( x != 0) {
int a = x % 10;
// 这样设置是考虑到ans的下一次循环将会溢出而x!=0,或者等于214748364,需要要跟最大数的末尾数字比较,如果这个数字比7还大,说明溢出了
if(ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE && ans > 7)) {
return 0;
} // 防止循环溢出,返回0
// 某个数字等于 -214748364,还需要跟最小数的末尾比较,即看它是否小于8
if(ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE && ans < -8)) {
return 0;
}
ans = ans * 10 + a;
x /= 10;
}
return ans;
}