LeetCode 7. 整数反转
题目描述
✅ 7. 整数反转
思路分析
解法一:逐位反转 + 溢出判断(推荐)
核心思路:
- 逐位弹出末位数字
digit = x % 10,将结果res = res * 10 + digit。- 在更新前判断是否会超过 32 位有符号整数范围。
- 超出范围返回 0。
复杂度分析:
- 时间复杂度:O(log n),其中 n 表示输入整数的绝对值。
- 空间复杂度:O(1),仅使用常数额外空间。
class Solution {
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;
}
}
func reverse(x int) int {
const maxInt32 = 1<<31 - 1
const minInt32 = -1 << 31
res := 0
for x != 0 {
digit := x % 10
x /= 10
if res > maxInt32/10 || (res == maxInt32/10 && digit > 7) {
return 0
}
if res < minInt32/10 || (res == minInt32/10 && digit < -8) {
return 0
}
res = res*10 + digit
}
return res
}
相似题目
| 题目 | 难度 | 考察点 |
|---|---|---|
| 8. 字符串转换整数 (atoi) | 中等 | 数值处理 |
| 9. 回文数 | 简单 | 数值处理 |
| 66. 加一 | 简单 | 数值处理 |
| 43. 字符串相乘 | 中等 | 数值处理 |
| 50. Pow(x, n) | 中等 | 数值处理 |
本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
