LeetCode 7 整数反转,数学题,模 10 取最后一位,唯一坑点是溢出判断。
🟡 整数反转
32 位有符号整数反转,溢出返回 0。
123 → 321,-123 → -321,120 → 21
思路很直接:每次模 10 取个位数,加到结果末尾(res = res * 10 + digit),原数除以 10。关键在反转后的数可能超过 int 范围(比如 2147483647 反转过来就爆了),Java 里需要在溢出之前提前判断。
java
public int reverse(int x) {
int res = 0;
while (x != 0) {
int digit = x % 10;
// 提前判断下次运算会不会溢出
if (res > Integer.MAX_VALUE / 10 ||
(res == Integer.MAX_VALUE / 10 && digit > 7)) return 0;
if (res < Integer.MIN_VALUE / 10 ||
(res == Integer.MIN_VALUE / 10 && digit < -8)) return 0;
res = res * 10 + digit;
x /= 10;
}
return res;
}
为什么是 7 和 -8?Integer.MAX_VALUE = 2147483647(个位是 7),MIN_VALUE = -2147483648(个位是 -8)。在 res*10 之前判断------如果 res 已经大于 MAX/10,乘 10 必定溢出。如果刚好等于 MAX/10,新的个位数 digit 不能超过 7。负数同理。
这道题你踩过什么坑?或者你用别的语言实现过吗?评论区聊聊,回头复习也方便翻。