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