Next Power of 2

Source: Internet
Author: User

Next Power of 2

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

    IP 5    op 8         IP +    op         ip +    32     

There is plenty of solutions for this. Let us take the example of 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   
    

Example

    Let us try for +            pos = 5            p   = 32    

Use the LG () function to pull up the whole


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. I Nitialize:count = 0        B. While n! = 0                n = n>>1                count = count + 1/* Now count have the     position of set bit in result */    3  retur N (1 << count)  

Example:

    Let us try for                 page count = 5                 p     = 32   

The position of the highest 1 in the binary of the number n
1#include <iostream>2#include <ctime>3 using namespacestd;4 5UnsignedintNEXTPOWEROF2 (intN) {6         /*First n in the below condition are for the case where n is 0*/7     if(n &&!) (N & (n1)))8         returnN;9     intCNT =0;Ten      while(n! =0){ OneN >>=1; Acnt++; -     } -     return(1<<CNT); the }  -  - intMain () { -cout << NextPowerOf2 ( -) <<Endl; +cout << NextPowerOf2 ( -) <<Endl; -     return 0; +}

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


Next Power of 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.