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 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 ; the check 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