Problem Statement
Power of Two
You are given a whole number n. Return true if n is a power of two, and false if it is not. A power of two is any number you get by multiplying 2 by itself some number of times: 1, 2, 4, 8, 16, 32, and so on. Put another way, n is a power of two if there is some whole number x where n equals 2 raised to the x power (2^x). Note that 2^0 equals 1, so 1 counts as a power of two.
Signals to notice
Brute force first
Divide by 2 repeatedly until you reach 1 or an odd number. Each division checks one bit, but you're doing it the slow way. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.
The key insight
n & (n - 1) == 0 checks if only one bit is set. A power of 2 in binary is 1 followed by zeros (e.g., 8 = 1000). Subtracting 1 flips all those zeros to ones (7 = 0111). AND-ing them gives 0 only when exactly one bit was set. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
Trace it on n=16
Guard: n=16 > 0, so skip the `n <= 0` return False Compute n-1: 16 in binary = 10000, so 15 = 01111 AND: 10000 & 01111 = 00000 (no shared set bits) -> result = 0 Check: (n & (n-1)) == 0 is (0 == 0) -> True Return True (16 = 2^4, exactly one bit set)
What must stay true
A power of 2 has exactly one bit set in its binary representation. n & (n-1) clears the lowest set bit — if the result is 0, there was only one bit to begin with. If that remains true after every update, the rest of the reasoning has a stable place to stand.
Shape of the loop
function isPowerOfTwo(n):
if n <= 0:
return false
return (n AND (n - 1)) == 0 # clears lowest set bit; 0 means exactly one bitPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Forgetting that 0 is not a power of 2 — you need n > 0 as an additional check, since 0 & (-1) = 0. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.