Wednesday, August 16, 2006

Next Power of 2

Given a number N, find out the nearest power of 2 which is greater than or equal to N..

int Closest(int x)
{
int higher = 1;
int orig = x;
while( x greaterThan 0 )
{
x = x rightShift 1;
higher = higher leftShift 1;
}
if(orig * 2 == higher)
return orig;
else
return higher;
}

4 comments:

Anonymous said...

this is a good question

Sayan said...

void nearest_power2(int x)
{
int temp=1;

if(x&&!(x&(x-1)))
return x;
else
{
while(x)
{
x>>=1;
temp<<=1;
}
return temp;
}
}

Anonymous said...

int power(int x)
{
int value = 1;
while (value <= x)
{
value = value << 1;
}
return value;
}


Wont this work?

Clemens said...

int power(int x) {
double foo = (double) x;
next = pow(ceil(log2(foo)),2);
return (int) next;
}