Next Power of 2

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.

    IP 5
    OP 8     

    IP 17
    OP 32     

    IP 32
    OP 32     

There are plenty of solutions for this. Let us take the example of 17 to explain some of them.


Method 1(Using Log of the number)

    1.  Calculate Position of set bit in p(next power of 2):
        pos =  ceil(lgn)  (ceiling of log n with base 2)
    2.  Now calculate p:
        p   = pow(2, pos) 

Example

    Let us try for 17
            pos = 5
            p   = 32    

利用lg()函数再向上取整


Method 2 (By getting the position of only set bit in result )

    /* If n is a power of 2 then return n */
    1  If (n & !(n&(n-1))) then return n 
    2  Else keep right shifting n until it becomes zero 
        and count no of shifts
        a. Initialize: count = 0
        b. While n ! = 0
                n = n>>1
                count = count + 1

     /* Now count has the position of set bit in result */
    3  Return (1 << count)  

Example:

    Let us try for 17
                 count = 5
                 p     = 32   

算得数n的二进制中最高位1的位置
 1 #include <iostream>
 2 #include <ctime> 
 3 using namespace std;
 4 
 5 unsigned int nextPowerOf2(int n){
 6         /* First n in the below condition is for the case where n is 0*/
 7     if(n && !(n & (n-1)))
 8         return n;
 9     int cnt = 0;
10     while(n != 0){
11         n >>= 1;
12         cnt++;
13     }
14     return (1 << cnt);
15 } 
16 
17 int main(){
18     cout << nextPowerOf2(16) << endl;
19     cout << nextPowerOf2(17) << endl;
20     return 0;
21 }

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


原文地址:https://www.cnblogs.com/qinduanyinghua/p/5745530.html