Leetcode - 7. 整数反转
解题思路参考代码中的注释:
class Solution {
private static int threshold = Integer.MAX_VALUE / 10;
// 检查sum * 10 + num是否会超过int的表示范围
// 如果sum大于threshold,则肯定溢出;如果sum小于threshold,则肯定不溢出
// 如果sum正好等于threshold,则num大于7时会溢出
private static boolean willOverflow(int sum, int num) {
return sum != threshold ? sum > threshold : num > 7;
}
public int reverse(int x) {
if (x == 0 || x == Integer.MIN_VALUE) {
return 0;
}
// c代表x的绝对值,sign用于表示x的正负性质
int sign = 1, c = x;
if (x < 0) {
sign = -1;
c = -c;
}
// 对正整数c进行反转
int sum = 0;
while(c > 0) {
int remainder = c % 10;
// 如果会发现溢出,则直接返回0
if(willOverflow(sum, remainder)) {
return 0;
}
sum = sum * 10 + remainder;
c /= 10;
}
// sum是正数,需要再乘以sign以保证最终的sum和x符号相同
return sum * sign;
}
}

