题目链接:7. Reverse Integer
难度:Easy
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
要点
本题考查的是整数相加的溢出处理,检查溢出有这么几种办法:
- 两个正数数相加得到负数,或者两个负数相加得到正数,但某些编译器溢出或优化的方式不一样
- 对于正数,如果最大整数减去一个数小于另一个数,或者对于负数,最小整数减去一个数大于另一个数,则溢出。这是用减法来避免加法的溢出。
- 使用long来保存可能溢出的结果,再与最大/最小整数相比较
Java
class Solution {
public int reverse(int x) {
int res = 0;
while (x != 0) {
if (Math.abs(res) > Integer.MAX_VALUE / 10) return 0;
res = res * 10 + x % 10;
x /= 10;
}
return res;
}
};
本文介绍了一个简单的算法问题——反转整数,并详细探讨了如何在反转过程中处理整数溢出的问题。提供了Java代码示例,通过判断变量在乘以10加上个位数之后是否仍处于有效范围内来确保不发生溢出。

942

被折叠的 条评论
为什么被折叠?



