【问题标题】:How to handle addition and subtraction beyond Integers MAX_VALUE and MIN_VALUE?如何处理超出整数 MAX_VALUE 和 MIN_VALUE 的加减法?
【发布时间】:2021-05-08 21:35:33
【问题描述】:

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

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。

我确信必须有一种更具体的方法来进行饱和。

【问题讨论】:

    标签: java integer overflow underflow saturation-arithmetic


    【解决方案1】:

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

    除非resultlong,否则无需检查result &gt;= Integer.MAX_VALUE 等条件以防正溢出或result &lt;= 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
    

    【讨论】:

      【解决方案2】:

      可以这么简单地完成:

      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.MIN_VALUE), 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-30
        • 1970-01-01
        • 2020-03-16
        • 2015-02-16
        • 2021-05-27
        • 2020-02-15
        • 2017-03-25
        • 1970-01-01
        相关资源
        最近更新 更多