If a number is a power of 2, it has one set bit in its binary representation and all other bits are unset.
Here is the binary representation of powers of 2:
$$\begin{aligned}
2^0 & = 1 & = 0001\_b \\
2^1 & = 2 & = 0010\_b \\
2^2 & = 4 & = 0100\_b \\
2^3 & = 8 & = 1000\_b \\\end{aligned}$$
As you can see, these binary representations only have one bit set (one β1β) and the rest are zeroes. This is a defining characteristic of powers of 2.
We can express this characteristic using bit manipulation. If βnβ is a power of 2, then βnβ AND βn-1β will be β0β.
Letβs examine this. If βnβ is a power of 2, we have a binary representation like β1000...0β. Now, βn-1β will be β0111...1β. When we do a bitwise AND operation (β&β), every bit of the result will be β0β because β1β AND β0β yields β0β and β0β AND β1β also yields β0β.
More formally, letβs represent the number as 2k. Then the binary representation of 2k in a sufficiently large number of bits is:
2kβ=β1000...0
And 2kβ ββ 1 is:
2kβ
ββ
1β=β0111...1
So, the bitwise AND of these two numbers:
2k&(2kβ
ββ
1)β=β0000...0β=β0
You can implement this as a function in any language that supports bitwise operations. For example, in Java:
boolean isPowerOfTwo(int n) {
if(n <= 0) return false;
return (n & (n - 1)) == 0;
}
This function first checks if the number is positive (since the method doesnβt work for negatives or zero), then it returns whether βn & (n - 1) == 0β. If βnβ is power of 2, this will be βtrueβ, otherwise βfalseβ.