Explanation of the safe average of two numbers

前端 未结 7 1302
离开以前
离开以前 2021-02-08 14:26

Whenever I need to average two numbers for an algorithm like binary search, I always do something like this:

int mid = low + ((high - low) / 2);
<
7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-08 14:55

    You are safe from integer overflows by using the way you said you already use, which is:

    int mid = low + ((high - low) / 2);
    

    Let you compiler do it's job to optimize this if it needs to.

提交回复
热议问题