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

后端 未结 2 1595
陌清茗
陌清茗 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.

提交回复
热议问题