Power of Two
Pattern: Bits basics
A power of two has exactly one set bit. n & (n - 1) clears the lowest set bit, so for a positive n it is 0 exactly when n is a power of two.
The problem
Given a 32-bit integer n, return whether it is a power of two, that is 2^k for some whole number k ≥ 0. For example,
1 and 16 give true, while 3, 0 and -16 give false.
The function name isPowerOfTwo matches LeetCode. Use the link above for the exact statement and limits. LeetCode asks
whether it can be done without loops.
Think first
- What do powers of two look like in binary?
- What does subtracting 1 do to the bits of a number?
- Which values must be ruled out before any bit test?
Hints
Brute force, and why it fails
Divide by 2 while even and check you reach 1: O(log n). Comparing with all 31 powers is O(31). The bit trick is O(1).
The key insight
"Exactly one set bit" is the same as "clearing the lowest set bit leaves nothing".
Dry run
n = 16, which is 10000 in binary.
The plan
return n > 0 and (n & (n - 1)) == 0
Complexity
- Time
O(1)- Space
O(1)
Two operations and a comparison.
Edge cases
n = 1: true, since2^0 = 1.n = 0: false.0 & -1is 0, so then > 0check matters.- The most negative int has one set bit in two's complement but is negative, so false.
I've built my logic, show the code
Java
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0; // n - 1 flips the lowest set bit and everything below it
}
}C++
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0; // n - 1 flips the lowest set bit and everything below it
}
};Python
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and n & (n - 1) == 0 # n - 1 flips the lowest set bit and everything below itCommon mistakes
- Forgetting
n > 0. - Writing
n & (n - 1) == 0without brackets in Java or C++, where==binds tighter. - Using floating-point logarithms, which can round wrongly.