I would like to calculate (x + y)/2 for any two integers x, y in Java. The naive way suffers from problems if x + y> Integer.MAX_VALUE, or <Integer.MIN_VALUE.
Guava IntMath uses this technique:
public static int mean(int x, int y) {
... but this is rounded to negative infinity, that is, the subroutine is not consistent with the naive way for values ββlike {-1, -2} (giving -2, not -1).
Is there any appropriate procedure that truncates in the 0 direction?
βJust use long β is not the answer I'm looking for since I need a method that also works for long inputs. BigInteger also not the answer I'm looking for. I do not want a solution with any branches.
java math bit-manipulation overflow
BeeOnRope
source share