You can use bitwise AND (&) operator :
return (num & -num) == num
Why does it work?
Consider the number 8, what is it in binary (assuming 32 bits)?
0000 0000 0000 0000 0000 0000 0000 1000
Now let's see how -8 is presented? one
1111 1111 1111 1111 1111 1111 1111 1000
Finally, let me calculate 8 & -8 :
0000 0000 0000 0000 0000 0000 0000 1000 8 ββββ ββββ ββββ ββββ ββββ ββββ ββββ ββββ & 1111 1111 1111 1111 1111 1111 1111 1000 -8 --------------------------------------- 0000 0000 0000 0000 0000 0000 0000 1000 8 Β―\_(γ)_/Β―
Now let's take another example, say 7 , which does not matter.
0000 0000 0000 0000 0000 0000 0000 0111 7 ββββ ββββ ββββ ββββ ββββ ββββ ββββ ββββ & 1111 1111 1111 1111 1111 1111 1111 1001 -7 --------------------------------------- 0000 0000 0000 0000 0000 0000 0000 0001 != 7 Β―\_(Ψ©_Ψ©)_/Β―
As @arshajii already mentioned, think about what happens if num is zero. I will leave a solution for you :)
1 A good way to remember how to calculate this: Start with the rightmost bit, for every 0 you see, donβt change it when you see 1, leave it and continue, but from now on, invert all the bits. I tried to explain it more here .
Maroun Oct 15 '13 at 14:05 2013-10-15 14:05
source share