Skip to content

Bit trick to detect powers of two

Question

How can you check quickly whether a given integer is a power of two?

Short answer

Test n > 0 && (n & (n - 1)) == 0. A power of two has exactly one bit set, and subtracting 11 flips that bit and turns on all lower bits, so the AND is zero; any other positive integer keeps its highest set bit. This is O(1)O(1); the check n>0n>0 excludes zero and negatives.

Adapted from Zhou, A Practical Guide to Quantitative Finance Interviews, sec. 7.2 The Power of Two, 'Power of 2?', p.181; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question