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:
this is a good question
void nearest_power2(int x)
{
int temp=1;
if(x&&!(x&(x-1)))
return x;
else
{
while(x)
{
x>>=1;
temp<<=1;
}
return temp;
}
}
int power(int x)
{
int value = 1;
while (value <= x)
{
value = value << 1;
}
return value;
}
Wont this work?
int power(int x) {
double foo = (double) x;
next = pow(ceil(log2(foo)),2);
return (int) next;
}
Post a Comment