Learning Outcome
After this lesson, you should be able to recognize the one-set-bit property of powers of two.
Problem Statement
Given an integer n, return true if it is a power of two.
| Input | Output | Why |
|---|---|---|
n = 16 | true | 16 is binary 10000, which has exactly one set bit. |
Brute Force Approach
Repeatedly divide by 2 until the number becomes odd. This works but is longer and easy to mishandle for zero or negative values.
Optimized Approach
A positive power of two has one set bit. n & (n
- clears the lowest set bit, so the result is zero only when there was one set bit.
Exact Pseudocode
if n <= 0:
return false
return (n & (n - 1)) == 0
Reference Code
class Solution:
def isPowerOfTwo(self, n):
return n > 0 and (n & (n - 1)) == 0Sample Dry Run
| Step | State | Result |
|---|---|---|
| n = 16 | binary 10000 | one set bit |
n
| binary 01111 | lower bits become 1 |
n & (n | 10000 & 01111 = 00000 | true |
| n = 18 | 10010 & 10001 is not zero | false |
Complexity
| Measure | Value | Reason |
|---|---|---|
| Time | O(1) | The check uses constant-time bit operations. |
| Space | O(1) | No extra data structure is used. |
Edge Cases
- Zero is not a power of two.
- Negative numbers are not powers of two.
- Do the n > 0 check before trusting the bit expression.
Interview Checklist
- Remember the one-set-bit property.
Use n & (n
- to remove the lowest set bit.
- Guard against n <= 0.
FAQs
Why does zero need a separate check?
0 & -1 is 0, so without n > 0, zero would incorrectly pass.
What does n & (n
- do?
- do?
It clears the lowest set bit of n.
What is the core pattern?
Single-set-bit check.