It can be done as simply as:
return Math.min(Math.max((long) n1 + n2, Integer.MIN_VALUE), Integer.MAX_VALUE);
The operation (long) n1 + n2
ensures that the result is a long
so that n1 + n2
neither overflows nor underflows.
The Math.max((long) n1 + n2, Integer.MIN_VALUE)
ensure that in the case n1 + n2
would have underflow we get the value Integer.MIN_VALUE
. Otherwise, we get the result of n1 + n2
.
Finally, Math.min(.., Integer.MAX_VALUE)
ensures that if n1 + n2
would have overflows the method returns Integer.MAX_VALUE
. Otherwise, the operation n1 + n2
will be returned instead.
Running example:
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