How to check if a number is a power of 2

后端 未结 25 1454
爱一瞬间的悲伤
爱一瞬间的悲伤 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:15
    private static bool IsPowerOfTwo(ulong x)
    {
        var l = Math.Log(x, 2);
        return (l == Math.Floor(l));
    }
    
    0 讨论(0)
  • 2020-11-22 04:16

    Some sites that document and explain this and other bit twiddling hacks are:

    • http://graphics.stanford.edu/~seander/bithacks.html
      (http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2)
    • http://bits.stephan-brumme.com/
      (http://bits.stephan-brumme.com/isPowerOfTwo.html)

    And the grandaddy of them, the book "Hacker's Delight" by Henry Warren, Jr.:

    • http://www.hackersdelight.org/

    As Sean Anderson's page explains, the expression ((x & (x - 1)) == 0) incorrectly indicates that 0 is a power of 2. He suggests to use:

    (!(x & (x - 1)) && x)
    

    to correct that problem.

    0 讨论(0)
  • 2020-11-22 04:18

    return (i & -i) == i

    0 讨论(0)
  • 2020-11-22 04:18

    The following addendum to the accepted answer may be useful for some people:

    A power of two, when expressed in binary, will always look like 1 followed by n zeroes where n is greater than or equal to 0. Ex:

    Decimal  Binary
    1        1     (1 followed by 0 zero)
    2        10    (1 followed by 1 zero)
    4        100   (1 followed by 2 zeroes)
    8        1000  (1 followed by 3 zeroes)
    .        .
    .        .
    .        .
    

    and so on.

    When we subtract 1 from these kind of numbers, they become 0 followed by n ones and again n is same as above. Ex:

    Decimal    Binary
    1 - 1 = 0  0    (0 followed by 0 one)
    2 - 1 = 1  01   (0 followed by 1 one)
    4 - 1 = 3  011  (0 followed by 2 ones)
    8 - 1 = 7  0111 (0 followed by 3 ones)
    .          .
    .          .
    .          .
    

    and so on.

    Coming to the crux

    What happens when we do a bitwise AND of a number x, which is a power of 2, and x - 1?

    The one of x gets aligned with the zero of x - 1 and all the zeroes of x get aligned with ones of x - 1, causing the bitwise AND to result in 0. And that is how we have the single line answer mentioned above being right.


    Further adding to the beauty of accepted answer above -

    So, we have a property at our disposal now:

    When we subtract 1 from any number, then in the binary representation the rightmost 1 will become 0 and all the zeroes to the left of that rightmost 1 will now become 1.

    One awesome use of this property is in finding out - How many 1s are present in the binary representation of a given number? The short and sweet code to do that for a given integer x is:

    byte count = 0;
    for ( ; x != 0; x &= (x - 1)) count++;
    Console.Write("Total ones in the binary representation of x = {0}", count);
    

    Another aspect of numbers that can be proved from the concept explained above is "Can every positive number be represented as the sum of powers of 2?".

    Yes, every positive number can be represented as the sum of powers of 2. For any number, take its binary representation. Ex: Take number 117.

    The binary representation of 117 is 1110101
    
    Because  1110101 = 1000000 + 100000 + 10000 + 0000 + 100 + 00 + 1
    we have  117     = 64      + 32     + 16    + 0    + 4   + 0  + 1
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 04:19

    I see many answers are suggesting to return n && !(n & (n - 1)) but to my experience if the input values are negative it returns false values. I will share another simple approach here since we know a power of two number have only one set bit so simply we will count number of set bit this will take O(log N) time.

    while (n > 0) {
        int count = 0;
        n = n & (n - 1);
        count++;
    }
    return count == 1;
    

    Check this article to count no. of set bits

    0 讨论(0)
提交回复
热议问题