How to check if a number is a power of 2

后端 未结 25 2230
爱一瞬间的悲伤
爱一瞬间的悲伤 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 03:55

    Example

    0000 0001    Yes
    0001 0001    No
    

    Algorithm

    1. Using a bit mask, divide NUM the variable in binary

    2. IF R > 0 AND L > 0: Return FALSE

    3. Otherwise, NUM becomes the one that is non-zero

    4. IF NUM = 1: Return TRUE

    5. Otherwise, go to Step 1

    Complexity

    Time ~ O(log(d)) where d is number of binary digits

提交回复
热议问题