我一直在研究 Apache 的通用数学库 Link
在下面的代码片段中,A、B、C 行对我来说没有意义。有人可以阐明这一点吗?
public static long subAndCheck(long a, long b) throws MathArithmeticException {
long ret;
if (b == Long.MIN_VALUE) { ----------A
if (a < 0) { --------------------B
ret = a - b; ----------------C
} else {
throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_ADDITION, a, -b);
}
} else {
// use additive inverse
ret = addAndCheck(a, -b, LocalizedFormats.OVERFLOW_IN_ADDITION);
}
return ret;
}
private static long addAndCheck(long a, long b, Localizable pattern) throws MathArithmeticException {
final long result = a + b;
if (!((a ^ b) < 0 || (a ^ result) >= 0)) {
throw new MathArithmeticException(pattern, a, b);
}
return result;
}
最佳答案
所以,Long.MIN_VALUE == -(Long.MAX_VALUE + 1) == -Long.MAX_VALUE - 1
,特别是 Long.MIN_VALUE == -Long.MIN_VALUE
.所以如果a >= 0
, 加/减 Long.MIN_VALUE
总会产生溢出。这意味着这是一种特殊情况,该方法必须测试 (A) 并且只有在 a < 0
时才执行实际减法。 (二).由于我们已经测试了可能的溢出,我们可以简单地执行 (C)。
关于java - 减去 2 个多头时的溢出检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42343004/