The following is the piece of code I am trying to implement:
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;
}
but I am not getting satisfactory results. For example, -2147483640-10 gives me 2147483646.
I am sure there has to be a more concrete way of doing saturation.
It can be done as simply as:
The operation
(long) n1 + n2
ensures that the result is along
so thatn1 + n2
neither overflows nor underflows.The
Math.max((long) n1 + n2, Integer.MIN_VALUE)
ensure that in the casen1 + n2
would have underflow we get the valueInteger.MIN_VALUE
. Otherwise, we get the result ofn1 + n2
.Finally,
Math.min(.., Integer.MAX_VALUE)
ensures that ifn1 + n2
would have overflows the method returnsInteger.MAX_VALUE
. Otherwise, the operationn1 + n2
will be returned instead.Running example:
OUTPUT: