为什么1534236469无法通过

时间:2019-11-25 10:34:25

标签: java

我认为1534236469超出范围! Leetcode:7.反向整数 我无法通过测试输入1534236469。为什么?返回范围为[Integer.MAX_VALUE,Integer.MIN_VALUE],其他应返回零

class Solution {
    public int reverse(int x) {
        if(x > Integer.MAX_VALUE || x < Integer.MIN_VALUE)
            return 0;
        int ans = 0;
        while(x != 0) {
            ans = ans * 10 + (x % 10);
            x /= 10;
        }
        return ans;
    }
}

感谢您的帮助

1 个答案:

答案 0 :(得分:5)

1534236469的倒数为9646324351,比Integer.MAX_VALUE大,因此您的代码将导致数字溢出和错误的结果。

您可以使用long而不是int来解决问题。

编辑:

您添加的if(x > Integer.MAX_VALUE || x < Integer.MIN_VALUE)条件毫无意义,因为xint,所以它永远不会超出int s的有效范围。

即使x在有效范围内,x的倒数也可能在范围之外。如果要检测到反转的x太大并返回0,则应在内部使用long

class Solution {
    public int reverse(int x) {
        long ans = 0;
        while(x != 0) {
            ans = ans * 10 + (x % 10);
            x /= 10;
        }
        if(ans > Integer.MAX_VALUE) {
            return 0;
        } else {
            return (int) ans;
        }
    }
}