Next Power of 2

来源:互联网 发布:linux telnet 端口测试 编辑:程序博客网 时间:2024/06/08 16:47

reference: 

http://www.geeksforgeeks.org/next-power-of-2/


Problem Definition:

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.


Solution:

1.Shift result one by one, this is straight-forward

2.Customized and Fast

    2.1. Subtract n by 1       n = n -1    2.2. Set all bits after the leftmost set bit.    /* Below solution works only if integer is 32 bits */                n = n | (n >> 1);                n = n | (n >> 2);                n = n | (n >> 4);                n = n | (n >> 8);                n = n | (n >> 16);    2.3. Return n + 1

Code:

1.Shift result one by one, this is straight-forward

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


2.Customized and Fast

/* Finds next power of two for n. If n itself   is a power of two then returns n*/ unsigned int nextPowerOf2(unsigned int n){    n--;    n |= n >> 1;    n |= n >> 2;    n |= n >> 4;    n |= n >> 8;    n |= n >> 16;    n++;    return n;}


原创粉丝点击