Understand
30-second explanation
Build the interview-ready mental model before comparing implementations.
A positive number is a power of two exactly when its binary form has a single 1 bit. The one-line test is `n > 0 && (n & (n - 1)) == 0`. Subtracting 1 flips the lowest set bit and turns everything below it to 1; ANDing with the original clears that lowest bit. If the result is 0, there was only one bit set. The `n > 0` guard rejects zero and negatives.
Interview contextWhat is testedWhere candidates slipHow to stand outExplore interview contextHide interview context
What's being tested
Whether you connect 'power of two' to 'one bit set' and know the n & (n-1) identity, plus whether you remember the zero/negative guard.
Where candidates slip
Forgetting the n > 0 guard, so n = 0 wrongly returns true, or reaching for a divide-by-two loop and missing the O(1) trick.
How to stand out
State the binary insight first, show n & (n-1), explain what subtracting 1 does to the bits, and mention the n & (-n) alternative.
Choose
Compare the available approaches
Use constraints and trade-offs to select the route you can defend in an interview.
Interactive decision treeInteractiveChoose the right approachFirst decision previewIs n a power of two?Need O(1)?No, warm-upYesExplore the full treeCollapse the tree
Learn & trace
Build each solution step by step
Move from the core idea to a visual trace, implementation, proof, and edge cases.
Approach 1 of 2
Divide-by-Two Loop (Warm-Up)
1Hint 1Explore hintHide hint
A power of two keeps halving cleanly down to 1. What happens to a non-power along the way?
2Hint 2Explore hintHide hint
While n is greater than 1 and even, divide it by 2. If you ever hit an odd number above 1, it wasn't a power of two.
3Hint 3Explore hintHide hint
After the loop, n is a power of two iff it landed exactly on 1. Guard n ≤ 0 up front.
A · Core idea
Repeatedly strip a factor of 2 and see whether you land on 1.
The idea. Every power of two divides evenly by 2 all the way down: 16 → 8 → 4 → 2 → 1. A number with any odd factor stalls — 6 → 3, and 3 is odd and bigger than 1, so 6 is not a power of two.
The guard. Numbers ≤ 0 can never be powers of two, so return false immediately for them; otherwise the loop on 0 or negatives misbehaves.
The loop. While n is even and greater than 1, divide by 2. When the loop ends, n is a power of two exactly when it equals 1.
Why we move past this. It is correct and only O(log n), but it loops where a single bitwise expression would do. Show it to demonstrate understanding, then present the O(1) trick.
B · Visual dry run
Interactive dry run
Select a frame to connect the decision with its visual state.
n = 16Array state
start
16 even
trueC · Code with teaching comments
Reference implementation previewpublic boolean isPowerOfTwo(int n) { if (n <= 0) return false; while (n % 2 == 0) { n /= 2; }Explore the full codeHide the full code
D · Why it works and complexityO(log n) timeO(1) spaceOpen the invariant and proofExplore the proofHide the proof
Halving is just a right shift, and 'is it still even?' is just 'is the lowest bit 0?'. That observation is the bridge from this loop to the constant-time bit trick.
ComplexityO(log n) time, O(1) space — Each iteration halves n, so there are at most log₂(n) iterations. Only a couple of integer variables are used, so space is O(1).
E · Edge cases and pitfalls3Skipping the n ≤ 0 guard — the loop misbehaves on 0 and negatives.Explore edge casesHide edge cases
Pitfalls
- Skipping the n ≤ 0 guard — the loop misbehaves on 0 and negatives.
- Returning true whenever the loop ends, instead of checking n == 1.
- Looping when an O(1) bit test is available — interviewers expect the trick.
Approach 2 of 2 · Optimal
Clear Lowest Set Bit — n & (n - 1) (Optimal)
1Hint 1Explore hintHide hint
Write a few powers of two in binary: 1, 10, 100, 1000. What do they all share?
2Hint 2Explore hintHide hint
Subtracting 1 from a number flips its lowest set bit to 0 and sets all bits below it to 1. What does ANDing that with the original do?
3Hint 3Explore hintHide hint
If n has a single set bit, n & (n-1) wipes it to 0. Add the n > 0 guard so 0 and negatives don't sneak through.
A · Core idea
Test for a single set bit by clearing the lowest one and checking nothing remains.
The binary fact. A power of two is 1 followed by zeros: 1, 10, 100, 1000. Exactly one bit is set. So 'is n a power of two?' becomes 'does n have exactly one set bit?' (for positive n).
What n - 1 does to the bits. Subtracting 1 finds the lowest set bit of n, flips it to 0, and turns every bit below it into 1. For n = 1000₂, n - 1 = 0111₂. For n = 1100₂, n - 1 = 1011₂ — the lowest set bit (position 2) cleared, the bit below it set.
Why the AND nails it. n & (n - 1) keeps only the bits set in both. Since n - 1 cleared n's lowest set bit and set everything below it (where n had zeros), the AND drops that lowest bit and preserves all higher bits of n. If n had just one bit, there are no higher bits, so the result is 0. If n had two or more bits, a higher bit survives and the result is non-zero.
The guard. For n = 0, n - 1 is all ones (-1), and 0 & -1 == 0, which would falsely report true — so n > 0 is required. Negatives have the sign bit set and are excluded by the same guard. That single comparison plus the AND is the whole O(1) solution.
B · Visual dry run
Interactive dry run
Select a frame to connect the decision with its visual state.
n = 6 (not a power) vs n = 8 (power)Array state
n = 8
binary 1000
8 → true, 6 → false, 0 → falseC · Code with teaching comments
D · Why it works and complexityO(1) timeO(1) spaceOpen the invariant and proofExplore the proofHide the proof
n & (n - 1) is the universal 'clear the lowest set bit' move — it powers Brian Kernighan's bit-count and many mask tricks. Recognizing that a power of two is the one-bit case turns the entire problem into a single application of it.
ComplexityO(1) time, O(1) space — A single subtraction, a single bitwise AND, and one comparison — all constant-time machine operations regardless of n. No extra memory.
E · Edge cases and pitfalls7n = 1 — 1 & 0 = 0 and 1 > 0 → true (2⁰).Explore edge casesHide edge cases
Edge cases handled
n = 11 & 0 = 0 and 1 > 0 → true (2⁰).n = 0Guard n > 0 fails → false, even though 0 & -1 = 0.n = -16Negative; guard rejects it → false despite |16| being a power of two.n = 2147483647 (2³¹ - 1)Many bits set, AND ≠ 0 → false; no overflow since no addition is done.
Pitfalls
- Dropping the n > 0 guard — 0 wrongly returns true because 0 & -1 == 0.
- Writing (n & (n - 1)) without parentheses — & has lower precedence than ==, so it parses wrong.
- Assuming it works on negatives — the sign bit makes the AND meaningless without the guard.
Practice
Try the solution yourself
Edit the optimal implementation, test another input, and observe the result.
Editable code previewpublic boolean isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; }Explore the playgroundClose the playground
Avoid mistakes
Recognize the interview traps
Understand why common attempts fail before reviewing the corrected implementation.
1Missing the positive guard
For n = 0, n - 1 is -1 (all ones), and 0 & -1 == 0, so without n > 0 the function falsely returns true for zero.
Explore the code comparisonHide the code comparison
Missing the positive guard
For n = 0, n - 1 is -1 (all ones), and 0 & -1 == 0, so without n > 0 the function falsely returns true for zero.
Don't write this
public boolean isPowerOfTwo(int n) {
return (n & (n - 1)) == 0; // 0 wrongly returns true
}Write this instead
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}2Operator precedence trap
In C-family languages == has higher precedence than &, so `n & (n - 1) == 0` parses as `n & ((n - 1) == 0)`, giving the wrong result.
Explore the code comparisonHide the code comparison
Operator precedence trap
In C-family languages == has higher precedence than &, so `n & (n - 1) == 0` parses as `n & ((n - 1) == 0)`, giving the wrong result.
Don't write this
return n > 0 && n & (n - 1) == 0; // parses as n & ((n-1)==0)Write this instead
return n > 0 && (n & (n - 1)) == 0; // parenthesize the ANDRevise
Carry the pattern into the interview
Pattern to remember
Single-set-bit test via n & (n - 1)
Code pattern to memorize
isPowerOfTwo(n) = (n > 0) && ((n & (n - 1)) == 0)Rules to remember
- 1
n & (n - 1)clears the lowest set bit. Zero result ⇒ there was only one set bit. - 2Always guard with
n > 0. Forn = 0,n & (n-1)is0 & -1 = 0, which would falsely pass. - 3Negatives are never powers of two; the
n > 0guard rejects them in one shot. - 4An alternative trick is
n & (-n) == n— isolate the lowest bit and check it equals n. - 5Avoid looping-divide-by-2 in interviews when the bit trick exists; mention the loop, then show the O(1) trick.
Use this pattern when
- Checking if a value is a single power of two (capacity sizing, hashing, alignment)
- Validating a number has exactly one bit set
- Bitmask code that requires power-of-two table sizes
- Any 'is this 2^k?' question on integers
Choose another pattern when
- Need the exponent k itself → use log2 / count trailing zeros, not just the boolean
- Power of four specifically → extra mask to confirm the bit sits in an even position
- Counting all set bits → Brian Kernighan's loop, not a single clear
- Floating-point inputs → the integer bit trick doesn't apply
Interview takeaway
Powers of two are the numbers with exactly one bit set, and `n & (n - 1)` clears the lowest set bit. So `(n & (n-1)) == 0` (with `n > 0`) is the whole test — an O(1), branch-light classic.
Continue
Transfer the pattern to another problem
Use a direct variation or pattern sibling to prove the idea is reusable.
Transferable patternPower-of-two detection is the one-set-bit special case of n & (n - 1), the universal lowest-set-bit clear. The same identity drives Number of 1 Bits, Counting Bits, and Power of Four.
Practice queueDirect variations and pattern siblings
Direct follow-ups
- Power of FourComing soonSame single-bit test, plus check the bit sits in an even position with a 0x55555555 mask.
- Number of 1 BitsCount set bits by repeatedly applying n &= (n - 1) — the same lowest-bit clear, looped.
- Power of ThreeComing soonNo clean bit trick for base 3 — use repeated division or the largest-power-of-three modulo trick.
- Counting BitsDP where bits[i] = bits[i & (i - 1)] + 1 reuses the lowest-bit-clear identity.