Overflow issues when implementing math formulas

前端 未结 4 934
陌清茗
陌清茗 2020-12-21 02:02

I heard that, when computing mean value, start+(end-start)/2 differs from (start+end)/2 because the latter can cause overflow. I do not quite understand why this second one

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-21 02:37

    In Binary Search, we will write the following code:

    if(start > end){
       return;
    }
    int mid = start + (end - start) / 2;
    

    By using start + (end - start) / 2, we can avoid the problems which are pointed by @dasblinkenlight

    if we use (start + end) / 2, it will overflow as shown by dasblinkenlight

提交回复
热议问题