If(a&-a==a)
Then the number is a power of 2.
It can be proved easily.
Let a=4, then a=00000100 (in 8 bit)
-a is the 2’s complement of a, then, -a=11111100
If we ANDing them then it only produce 1 in the 6th bit and all other is 0. It will be 00000100, that is the number a, and we know 4 it is a power of 2.
But if the number is otherwise, then it can’t results the same number. Because it has more 1 in it’s bit representation, that will be changed in 2’s complement and doesn’t produce the same number while ANDing. Try it yourself J
There is another way to find whether a number is a power of 2 or not. If there is only 1 in a bit representation of a positive number then it is a power of two.
Like,
2= 10
4=100
8=1000
16=10000
See, there is only one 1 in bit representation of this numbers.
We can detect it by this sample code:
#include<bitset>
bitset<16>num;
scanf(“%d”,&num);
ans=num.count();
if(ans==1)
printf("yes");
else
printf("no");
I found another process from zobayer vai's blog.
The process is: (just pasting from the post of zobayer vai )
Is a number a power of 2?
How can we check this? of course write a loop and check by repeated division of 2. But with a simple bit-wise operation, this can be done fairly easy.
We, know, the binary representation of p = 2
n is a bit string which has only 1 on the n
thposition (0 based indexing, right most bit is LSB). And p-1 is a binary number which has 1 on 0 to n-1 th position and all the rest more significant bits are 0. So, by AND-ing p and (p-1) will result 0 in this case:
No other number will show this result, like AND-ing 6 and 5 will never be 0.