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.
If you need to set limits to
Integer.MAX_VALUEandInteger.MIN_VALUEin case of overflow, you should track if sign of the result has changed to define when the overflow has taken place.Unless
resultislong, there's no need to check conditions likeresult >= Integer.MAX_VALUEin case of positive overflow orresult <= Integer.MAX_VALUEfor negative overflow.Tests:
Output: