How to check if a number is a power of 2

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

    int isPowerOfTwo(unsigned int x)
    {
        return ((x != 0) && ((x & (~x + 1)) == x));
    }
    

    This is really fast. It takes about 6 minutes and 43 seconds to check all 2^32 integers.

提交回复
热议问题