如何处理整数 MAX_VALUE 和 MIN_VALUE 以外的加法和减法?

问题描述

以下是我正在尝试实现的一段代码

if (n1 > 0 && n2 > 0 && result >= Integer.MAX_VALUE) {
    result = Integer.MAX_VALUE;
}
else if (n1 > 0 && n2 > 0 && (result <= Integer.MIN_VALUE || result < 0)) {
    result = Integer.MAX_VALUE;
}
else if (n1 < 0 && n2 < 0 && (result <= Integer.MIN_VALUE || result == 0)) {
    result = Integer.MIN_VALUE;
}

但我没有得到满意的结果。例如,-2147483640-10 给我 2147483646。

我确信必须有更具体的方法来实现饱和。

解决方法

如果您需要在溢出的情况下为 Integer.MAX_VALUEInteger.MIN_VALUE 设置限制,您应该跟踪结果的符号是否已更改以定义何时发生溢出。

除非 resultlong,否则无需检查条件,例如 result >= Integer.MAX_VALUE 表示正溢出或 result <= Integer.MAX_VALUE 表示负溢出。

public static int add(int n1,int n2) {
    System.out.printf("%d + %d = ",n1,n2);
    int result = n1 + n2;

    if (n1 > 0 && n2 > 0 && result < 0) {
        result = Integer.MAX_VALUE;
    } else if (n1 < 0 && n2 < 0 && result > 0) {
        result = Integer.MIN_VALUE;
    }

    return result;
}

测试:

System.out.println(add(10,20));
System.out.println(add(2147483640,10));

System.out.println(add(-10,-20));
System.out.println(add(-2147483640,-10));

输出:

10 + 20 = 30
2147483640 + 10 = 2147483647
-10 + -20 = -30
-2147483640 + -10 = -2147483648
,

它可以像这样简单地完成:

return Math.min(Math.max((long) n1 + n2,Integer.MIN_VALUE),Integer.MAX_VALUE);

操作 (long) n1 + n2 确保结果是 long,因此 n1 + n2 既不上溢,也不下溢

Math.max((long) n1 + n2,Integer.MIN_VALUE) 确保在 n1 + n2下溢的情况下,我们得到值 Integer.MIN_VALUE。否则,我们得到 n1 + n2 的结果。

最后,Math.min(..,Integer.MAX_VALUE) 确保如果 n1 + n2溢出,则该方法返回 Integer.MAX_VALUE。否则,将返回操作 n1 + n2

运行示例:

public class UnderOver {

    public static long add(int n1,int n2){
       return Math.min(Math.max((long) n1 + n2,Integer.MAX_VALUE);
    }

    public static void main(String[] args) {
        System.out.println(add(Integer.MAX_VALUE,10));
        System.out.println(add(Integer.MIN_VALUE,-10));
        System.out.println(add(-10,-10));
        System.out.println(add(10,10));
        System.out.println(add(10,0));
        System.out.println(add(-20,10));
    }
}

输出

2147483647
-2147483648
-20
20
10
-10