有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么反向操作允许溢出处理?

leetcode问题(https://leetcode.com/problems/reverse-integer/description/)要求反转一个整数,这很简单,但如果出现任何溢出,则希望用户返回0。使用long也很简单,因为您可以检查它是否大于整数。java中的MAX_INT或MIN_INT。但如果只允许32位整数,如何实现这一点

下面显示了以下解决方案:

public int reverse(int x)
{
    int result = 0;

    while (x != 0)
    {
        int tail = x % 10;
        int newResult = result * 10 + tail;
        if ((newResult - tail) / 10 != result)
        { return 0; }
        result = newResult;
        x = x / 10;
    }

    return result;
}

我不明白为什么会这样。为什么“反转”操作并将其与之前的结果进行比较成功地检查溢出

如果你从x开始,然后说: x2=(x*10)+b,(x2-b)/10不总是等于x吗?因为正溢出总是循环到最小值,而负溢出总是循环到最大值。如何检查溢出?我希望能澄清这一点


共 (1) 个答案

  1. # 1 楼答案

    If you started with x, then said: x2 = (x*10) + b, wouldn't (x2-b)/10 always equal x?

    不。你关于“循环”的直觉对于加法和减法是正确的——就像12点左右在钟面上来回移动一样

    但是,这不适用于乘法,如本例所示:

    int x = 2_000_000_000;
    int y = x * 10;
    int z = y / 10;
    
    System.out.println(x);   // 2000000000
    System.out.println(z);   // -147483648
    

    Live demo.

    因此,要回答最重要的问题:

    Why does "reversing" the operation, and comparing it to the previous result successfully check for overflow?

    因为当溢出发生时,“反转”这个操作序列不会让你回到输入值