I\'d like a way to calculate (x + y)/2
for any two integers x, y in Java. The naive way suffers from issues if x+y > Integer.MAX_VALUE, or < Integer.MIN_VAL
Why don't you do something like (x-y)/2 + y
, which reduces to x/2 - y/2 + y = x/2 + y/2
? So if x+y
gives you an overflow or underflow, you do it the (x-y)/2 + y
way.
You need to add 1
to the result if the lowest bits are different (so the result is not exact and you need to round), and the sign bit in the result is set (the result is negative, so you want to change the round down into a round up).
So the following should do (untested):
public static int mean(int x, int y) {
int xor = x ^ y;
int roundedDown = (x & y) + (xor >> 1);
return roundedDown + (1 & xor & (roundedDown >>> 31));
}