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