Query about working out whether number is a power of 2

后端 未结 4 1306
情歌与酒
情歌与酒 2020-12-07 04:59

Using the classic code snippet:

if (x & (x-1)) == 0

If the answer is 1, then it is false and not a power of 2. However, working on 5 (not a power of 2) a

4条回答
  •  暖寄归人
    2020-12-07 05:43

    ((n & (n-1)) == 0)

    It checks whether the value of “n” is a power of 2.

    Example:

     if n = 8, the bit representation is 1000
     n & (n-1) = (1000) & ( 0111) = (0000)
     So it return zero only if its value is in power of 2.
     The only exception to this is ‘0’.
     0 & (0-1) = 0 but ‘0’ is not the power of two. 
    

    Why does this make sense?

    Imagine what happens when you subtract 1 from a string of bits. You read from left to right, turning each 0 to a 1 until you hit a 1, at which point that bit is flipped:

    1000100100 -> (subtract 1) -> 1000100011

    Thus, every bit, up through the first 1, is flipped. If there’s exactly one 1 in the number, then every bit (other than the leading zeros) will be flipped. Thus, n & (n-1) == 0 if there’s exactly one 1. If there’s exactly one 1, then it must be a power of two.

提交回复
热议问题