AlgoViz
← All problems

Power of Two

Easy+70 XPteaches: Bits & Binary

Given an integer `n`, return `true` if it is a power of two (2⁰, 2¹, 2², …) and `false` otherwise. Try to do it in O(1) with a single bitwise operation.

Example: n = 16 → true

Keep halving: Divide by 2 while even; it's a power of two iff you land exactly on 1. (time O(log n), space O(1))

No visualization loaded.

Watch

i

Press Run to begin.

Why the best approach wins

Halving works but loops about log n times. The bit trick is a single step: a power of two is exactly one ON switch, and subtracting 1 borrows through that switch, so n and n−1 share no bits — their AND is 0. One comparison, constant time, no loop.

Keep halving: O(log n) time / O(1) spacen & (n−1) trick: O(1) time / O(1) space

Your turn — implement isPowerOfTwo

Loading editor…