Kekis2014 Kekis2014 - 2 years ago 94
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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download