Kekis2014 Kekis2014 - 3 months ago 9
Java Question

Taking the Average of Integers (j+k)/2 when stack there is an Overflow

If there is an

int j = Integer.MAX_VALUE
and an
int k = Integer.MAX_VALUE
how can I compute the average (j+k)/2 so that the
result = Integer.MAX_VALUE
without causing an overflow.

Answer

In this case (j+k)/2 is the same as (j/2) + (k/2)

Correction as per bilalba

    int j = Integer.MAX_VALUE;
    int k = Integer.MAX_VALUE;

    int res = (j/2) + (k/2) + (j%2 & k%2);
    System.out.println(res);