首页 > Leetcode Reverse Integer 中的溢出处理

Leetcode Reverse Integer 中的溢出处理

原题有这样的提示

“Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?”

看到有人写了一个这样的答案

int reverse(int x) {
    int flag=x>0?1:-1,res=0;
    x=x>0?x:-x;
    while(x>0){
        if((2147483647.0-x%10)/10<res)return 0;
        res=res*10+x%10;
        x=x/10;
    }
    return res*flag;
}

这一句 if((2147483647.0-x%10)/10<res)return 0; 可以起到检查int x是否超出int的范围2147483647 这样的作用吗,能否详解一下?

这一句 if((2147483647.0-x%10)/10<res)return 0; 每一次循环都会轮一遍,那么它究竟是判断输入的x是否超出int,还是判断每一轮的结果result是否超出int。其实我一开始一直在想的是如何判断输入的int x是否溢出。但是好像溢出不仅仅只有负数的情况还有溢出过多只取后面几位的情况。

还有别的好方法可以判断输入的一个数是否超出int范围的方法吗?


(2147483647.0-x%10)/10<res 即是 2147483647.0 <(double)res*10 + x%10, 即转成了double型 做判断.

我的做法是直接 用long型:

public int reverse(int x) {
    int sign = 1;
    if(x < 0){
        sign = -1;
        x *= -1;
    }

    long result = 0;
    while(x != 0){
        result = result * 10 + x % 10;
        if(sign * result > Integer.MAX_VALUE ||
                sign * result < Integer.MIN_VALUE)
            return 0;
        x = x / 10;
    }

    return (int)result * sign;

它判断的是每轮的结果是否超过int
if((2147483647.0-x%10)/10<res)return 0;
变一下形,就是 2147483647.0 < res * 10 + x % 10
上面不等式的右边是每轮的结果,但是因为已经超过Integer.MAX_VALUE,为了避免溢出,用了

【热门文章】
【热门文章】