http://en.wikipedia.org/wiki/Power_of_2
unsigned int nextPowerOf2(unsigned int n){ unsigned count = 0; /* First n in the below condition is for the case where n is 0*/ if (n & !(n&(n-1))) return n; while( n != 0) { n >>= 1; count += 1; } return 1<<count;}
We can also shift result one by one instead of using count variable--------------------------------------unsigned int nextPowerOf2(unsigned int n){ unsigned int p = 1; if (n & !(n & (n - 1))) return n; while (p < n) { p <<= 1; } return p;}
http://www.geeksforgeeks.org/archives/475
unsigned int nextPowerOf2_Complicated(unsigned int n){ n--; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; n++; return n;}
http://en.wikipedia.org/wiki/Power_of_2
ReplyDeleteunsigned int nextPowerOf2(unsigned int n)
ReplyDelete{
unsigned count = 0;
/* First n in the below condition is for the case where n is 0*/
if (n & !(n&(n-1)))
return n;
while( n != 0)
{
n >>= 1;
count += 1;
}
return 1<<count;
}
We can also shift result one by one instead of using count variable
ReplyDelete--------------------------------------
unsigned int nextPowerOf2(unsigned int n)
{
unsigned int p = 1;
if (n & !(n & (n - 1)))
return n;
while (p < n) {
p <<= 1;
}
return p;
}
http://www.geeksforgeeks.org/archives/475
ReplyDeleteunsigned int nextPowerOf2_Complicated(unsigned int n)
ReplyDelete{
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}