How to check if a number is a power of 2

后端 未结 25 1530
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 03:30

Today I needed a simple algorithm for checking if a number is a power of 2.

The algorithm needs to be:

  1. Simple
  2. Correct for any ulong
25条回答
  •  你的背包
    2020-11-22 04:19

    for any power of 2, the following also holds.

    n&(-n)==n

    NOTE: fails for n=0 , so need to check for it
    Reason why this works is:
    -n is the 2s complement of n. -n will have every bit to the left of rightmost set bit of n flipped compared to n. For powers of 2 there is only one set bit.

提交回复
热议问题