What code will you write to check if a number is power of two or not?
💡Strategies for Solving This Problem
Bit Manipulation Gold
This is a 5-minute interview question that separates people who know bit tricks from those who don't. I learned this the hard way at Facebook.
The Naive Approach
Keep dividing by 2 until you hit 1 or an odd number. Works but it's O(log n) and shows you don't know the bit trick.
// Don't do this
function isPowerOfTwo(n) {
if (n <= 0) return false;
while (n % 2 === 0) {
n = n / 2;
}
return n === 1;
}
The Bit Trick
Powers of 2 in binary have exactly one bit set:
- 1 = 0001
- 2 = 0010
- 4 = 0100
- 8 = 1000
Key insight: n & (n-1) clears the lowest set bit. For power of 2, this gives 0.
Example:
- 8 = 1000
- 7 = 0111
- 8 & 7 = 0000 ✓
But for non-power-of-2:
- 6 = 0110
- 5 = 0101
- 6 & 5 = 0100 ✗ (not zero)
One-Liner Solution
return n > 0 && (n & (n - 1)) === 0;
That's it. O(1) time, O(1) space, and shows you know bit manipulation.
Why This Matters
My Facebook interviewer asked this as a warm-up. I gave the division approach. He said "Can you do it in O(1)?" I couldn't figure it out in time. Didn't get the offer.
Learn the bit tricks. They come up more than you'd think.