← Bit Manipulation

Pattern Recognition Drill

#84 — Power of two

Easy Bit Manipulation

The Problem

Check if n is a power of two.

What approach would you use?

Think about it before scrolling down.

Key Signals

Bit Manipulation

return n > 0 and n & (n-1) == 0. One operation, O(1).

Common Trap

Don't forget n > 0 check. n=0 gives 0 & (-1) = 0 which is a false positive.

← #83 #85 →