簡體   English   中英

如何處理超出整數 MAX_VALUE 和 MIN_VALUE 的加法和減法?

[英]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_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));

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM