Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何处理超出整数MAX_值和MIN_值的加减运算?_Java_Integer_Overflow_Underflow_Saturation Arithmetic - Fatal编程技术网

Java 如何处理超出整数MAX_值和MIN_值的加减运算?

Java 如何处理超出整数MAX_值和MIN_值的加减运算?,java,integer,overflow,underflow,saturation-arithmetic,Java,Integer,Overflow,Underflow,Saturation Arithmetic,以下是我试图实现的代码: if(n1>0&&n2>0&&result>=Integer.MAX\u值){ 结果=整数。最大值; } 否则,如果(n1>0&&n2>0&&(result如果需要将限制设置为Integer.MAX\u VALUE和Integer.MIN\u VALUE以防溢出,则应跟踪结果的符号是否已更改,以定义溢出发生的时间 除非result是long,否则在出现正溢出或result 0&&n2>0&&result=Integer.MAX_VALUE等条件{ 结果=整数。最大值;

以下是我试图实现的代码:

if(n1>0&&n2>0&&result>=Integer.MAX\u值){
结果=整数。最大值;
}

否则,如果(n1>0&&n2>0&&(result如果需要将限制设置为
Integer.MAX\u VALUE
Integer.MIN\u VALUE
以防溢出,则应跟踪结果的符号是否已更改,以定义溢出发生的时间

除非
result
long
,否则在出现正溢出或
result 0&&n2>0&&result<0)的情况下,无需检查
result>=Integer.MAX_VALUE
等条件{ 结果=整数。最大值; }否则如果(n1<0&&n2<0&&result>0){ 结果=整数.MIN_值; } 返回结果; }
测试:

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((长)n1+n2,Integer.MIN\u值)
确保在
n1+n2
的情况下,我们得到值
Integer.MIN\u值
。否则,我们得到
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