is power of 2
bool isPowerOfTwo(int n) {
if (n <= 0) {
return false;
}
return (n & (n - 1)) == 0;
}
Explanation:
bool isPowerOfTwo(int n)
: This function takes an integern
as input and returns a boolean value indicating whethern
is a power of 2.if (n <= 0) { return false; }
: Checks if the inputn
is less than or equal to 0. If it is, the function returnsfalse
because non-positive numbers cannot be powers of 2.(n & (n - 1)) == 0
: This expression uses a bitwise AND operation betweenn
and(n - 1)
. If the result of this operation is 0, it implies thatn
is a power of 2.
Explanation of (n & (n - 1))
:
- n - 1
decrements n
by 1.
- Bitwise AND (&
) operation between n
and n - 1
checks if there are no common set bits between n
and n - 1
. If n
is a power of 2, it has only one bit set, and subtracting 1 sets all bits before this set bit. The result of the bitwise AND will be 0 in this case.
Example:
Let's take n = 8
(which is a power of 2).
- Binary representation of 8
is 1000
.
- n - 1 = 7
, binary representation is 0111
.
- Bitwise AND operation between 8
and 7
(1000 & 0111
) results in 0000
, which equals 0.
- Thus, 8
is a power of 2.
This function combines these steps to determine if the given integer is a power of 2 by utilizing bitwise operations.