Tuesday, December 20, 2011

Next Power of 2

Write a function that, for a given no n, finds a number p which is greater than or equal to n and is a power of 2.

5 comments:

  1. http://en.wikipedia.org/wiki/Power_of_2

    ReplyDelete
  2. unsigned int nextPowerOf2(unsigned int n)
    {
    unsigned count = 0;

    /* First n in the below condition is for the case where n is 0*/
    if (n & !(n&(n-1)))
    return n;

    while( n != 0)
    {
    n >>= 1;
    count += 1;
    }

    return 1<<count;
    }

    ReplyDelete
  3. We can also shift result one by one instead of using count variable
    --------------------------------------

    unsigned int nextPowerOf2(unsigned int n)
    {
    unsigned int p = 1;
    if (n & !(n & (n - 1)))
    return n;

    while (p < n) {
    p <<= 1;
    }
    return p;
    }

    ReplyDelete
  4. http://www.geeksforgeeks.org/archives/475

    ReplyDelete
  5. unsigned int nextPowerOf2_Complicated(unsigned int n)
    {
    n--;
    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
    n++;
    return n;
    }

    ReplyDelete