How to check if a number is a power of 2

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

    A number is a power of 2 if it contains only 1 set bit. We can use this property and the generic function countSetBits to find if a number is power of 2 or not.

    This is a C++ program:

    int countSetBits(int n)
    {
            int c = 0;
            while(n)
            {
                    c += 1;
                    n  = n & (n-1);
            }
            return c;
    }
    
    bool isPowerOfTwo(int n)
    {        
            return (countSetBits(n)==1);
    }
    int main()
    {
        int i, val[] = {0,1,2,3,4,5,15,16,22,32,38,64,70};
        for(i=0; i

    We dont need to check explicitly for 0 being a Power of 2, as it returns False for 0 as well.

    OUTPUT

    Num:0   Set Bits:0   is power of two: 0
    Num:1   Set Bits:1   is power of two: 1
    Num:2   Set Bits:1   is power of two: 1
    Num:3   Set Bits:2   is power of two: 0
    Num:4   Set Bits:1   is power of two: 1
    Num:5   Set Bits:2   is power of two: 0
    Num:15  Set Bits:4   is power of two: 0
    Num:16  Set Bits:1   is power of two: 1
    Num:22  Set Bits:3   is power of two: 0
    Num:32  Set Bits:1   is power of two: 1
    Num:38  Set Bits:3   is power of two: 0
    Num:64  Set Bits:1   is power of two: 1
    Num:70  Set Bits:3   is power of two: 0
    

提交回复
热议问题