I want to find if a user entered number is a power of two or not.
My code doesn\'t work.
public class power_of_two
{
public static void main
You can use the bitwise AND (&) operator:
return (num & -num) == num
Why this works?
Consider the number 8, what it is in binary (assuming 32-bits)?
0000 0000 0000 0000 0000 0000 0000 1000
Now let's see how -8 is represented? 1
1111 1111 1111 1111 1111 1111 1111 1000
Finally.. let's 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, let's say 7
, which is not power of two.
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 mentioned by @arshajii, think what will happen if num
is zero.. I'll leave the solution for you :)
1 A good way to remember how to calculate that: Begin from the rightmost bit, for each 0 you see, don't change it, when you see 1, leave it and proceed, but from now on, invert all bits. I tried to explain this more here.