Finding if a number is a power of 2

前端 未结 7 1327
孤城傲影
孤城傲影 2021-02-18 18:15

Just out of curiosity, how can you tell if a number x is a power of two (x = 2^n) without using recursion.

Thanks

7条回答
  •  轮回少年
    2021-02-18 18:42

    One way is to use bitwise AND. If a number $x is a power of two (e.g., 8=1000), it will have no bits in common with its predecessor (7=0111). So you can write:

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

    Note: This will give a false positive for $x == 0.

提交回复
热议问题