开发者社区> 问答> 正文

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

这一句 if((2147483647.0-x%10)/10

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

展开
收起
a123456678 2016-06-08 15:09:05 1883 0
1 条回答
写回答
取消 提交回答
  • 我的做法是直接 用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;
    2019-07-17 19:32:02
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载