easyMathArrays & Hashing

Power of Two

easyTime: O(1)Space: O(1)

Signals to notice

check if number is exactly a power of 2single bit setbit manipulation

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.

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.

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.

Arrays & Hashing Pattern