Mean of two ints (or longs) without overflow, truncating towards 0

后端 未结 2 1571
陌清茗
陌清茗 2021-01-02 14:25

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

相关标签:
2条回答
  • 2021-01-02 15:08

    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.

    0 讨论(0)
  • 2021-01-02 15:10

    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));
    }
    
    0 讨论(0)
提交回复
热议问题