Explanation of the safe average of two numbers

前端 未结 7 1306
离开以前
离开以前 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条回答
  • 2021-02-08 15:12

    So let's consider bytes instead of ints. The only difference is that a byte is an 8-bit integer, while an int has 32 bits. In Java, both are always signed, meaning that the leading bit indicates whether they're positive (0) or negative (1).

    byte low = Byte.valueOf("01111111", 2); // The maximum byte value
    byte high = low; // This copies low.
    
    byte sum = low + high; // The bit representation of this is 11111110, which, having a
                           // leading 1, is negative. Consider this the worst case
                           // overflow, since low and high can't be any larger.
    
    byte mid = sum >>> 1; // This correctly gives us 01111111, fixing the overflow.
    

    For ints, it's the same thing. Basically the gist of all this is that using an unsigned bitshift on signed integers allows you to leverage the leading bit to handle the largest possible values of low and high.

    0 讨论(0)
提交回复
热议问题