[英]How to handle addition and subtraction beyond Integers MAX_VALUE and 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_VALUE
和Integer.MIN_VALUE
設置限制,您應該跟蹤結果的符號是否已更改以定義溢出發生的時間。
除非result
是long
,否則不需要檢查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));
Output:
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.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));
}
}
OUTPUT :
2147483647
-2147483648
-20
20
10
-10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.