Query about working out whether number is a power of 2

后端 未结 4 1310
情歌与酒
情歌与酒 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:37

    Keep in mind that if x is a power of 2, there is exactly 1 bit set. Subtract 1, and you know two things: the resulting value is not a power of two, and the bit that was set is no longer set. So, when you do a bitwise and &, every bit that was set in x is not unset, and all the bits in (x-1) that are set must be matched against bits not set in x. So the and of each bit is always 0.

    In other words, for any bit pattern, you are guaranteed that (x&(x-1)) is zero.

提交回复
热议问题