我希望有一种方法可以在Java中计算任意两个整数x,y的平均值(x+y)/2。朴素的方法会遇到问题,如果x+y>Integer.MAX_VALUE或<Integer.MIN_VALUE。
Guava的IntMath
使用了这种技术:
public static int mean(int x, int y) {
// Efficient method for computing the arithmetic mean.
// The alternative (x + y) / 2 fails for large values.
// The alternative (x + y) >>> 1 fails for negative values.
return (x & y) + ((x ^ y) >> 1);
}
但是这个方法向负无穷方向舍入,这意味着对于像{-1,-2}这样的值,该例程与朴素方式不一致(给出-2而不是-1)。
是否有任何相应的例程可以向0截断?
“只使用
long
”不是我要找的答案,因为我希望有一个适用于长输入的方法。 BigInteger
也不是我要找的答案。 我不想要任何分支的解决方案。