The bit representation of any number of the form 2^n will have only one field set.
If we do an AND operation with the (number-1) the result is 0
i.e (n & n-1) is 0
The number is of form 2^n if (n & n-1) is 0
#include <stdio.h>
int main()
{
int num;
printf("Enter number\n");
scanf("%d", &num);
if(num && !(num & num-1))
{
printf("The number is of form 2^n");
}
else
{
printf("The number is not of the form 2^n");
}
return 0;
}
No comments :
Post a Comment