Print the next power of 2 for a given number

Wednesday, February 13, 2013 , 0 Comments

Below is the program that I have written for printing the next power of 2 for a given number.
The code mostly uses the bitwise operations in c/c++.
int main ()
{
int num;
scanf("%d",&num);
int count=0;
        if(!((num != 1) && (num&(num-1))))
        {
        printf("%d is already a power of two.\n",num);
        printf("%d is next number power of 2.\n",num*2);
        }
        else
        {
        while((num>>=1)&&(++count));
        printf("%0.0f",pow(2.0,count+1));
        }
}

0 comments: