問題:計算 `(a + b) / 2` 當 `a,b` 為 `Integer.MAX_VALUE` 時溢出(結果為負數)。
int avg = (a & b) + ((a ^ b) >> 1);
對任意兩整數:
int avg = a / 2 + b / 2 + ((a % 2 + b % 2) / 2);
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class AvgBenchmark {
@Benchmark public int bitwise() { return (a & b) + ((a ^ b) >> 1); }
@Benchmark public int math() { return a/2 + b/2 + (a%2 + b%2)/2; }
@Benchmark public int cast() { return (int)((a + b) >>> 1); } // 無符號右移需 long 中轉
}
結果:位運算版與數學版性能接近,均優於 `long` 中轉版(無額外類型轉換開銷)。