整数反转
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123输出: 321
示例 2:
输入: -123输出: -321
示例 3:
输入: 120输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
判断溢出:比较最后一位
public int reverse(int x) {
int ans = 0;
while (x / 10 != 0) {
ans = ans * 10 + x % 10;
x /= 10;
}
ans = ans * 10 + x;
if (ans % 10 != x) {
return 0;
}
return ans;
}
public int reverse(int x) {
int ans = 0;
while (x != 0) {
int digit = x % 10;
ans = ans * 10 + digit;
x /= 10;
if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && digit > 7)) {
return 0;
}
if (ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE / 10 && digit < 8)) {
return 0;
}
}
return ans;
}