Next Power of 2

本文介绍了一种用于找出大于或等于给定数的最近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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值