Skip to content
DSA Patterns
Menu
Language
Bit ManipulationLC #2313 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Power of Two

Problem (restated)

Return true if n is a power of two (positive integer with exactly one bit set).

Intuition

Powers of two are 1,2,4,8… Clearing the lowest set bit of such n yields 0: n & (n-1) == 0, and n > 0.

Approaches

n & (n-1) == 0

Unverified
Time O(1)Space O(1)

Idea. Reject non-positive. One-liner bit trick.

Walkthrough. 16 → true; 3 → false; 0 → false.

Trade-offs. Log loop also works; bit check is O(1).

Solution
export function isPowerOfTwo(n: number): boolean {
  return n > 0 && (n & (n - 1)) === 0;
}
export function isPowerOfTwo(n: number): boolean {
  return n > 0 && (n & (n - 1)) === 0;
}

Template connection

A positive power of two has a single set bit: n > 0 && (n & (n - 1)) == 0.

Reflection

  • A power of two is positive and has one bit set: n > 0 and n & (n - 1) == 0.
  • 0 and every negative are false. 1 is true, because it is 2**0.
  • Two bits set means n - 1 does not clear both of them, so the AND is not 0.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

A power of two has exactly one bit set. Check 16 = 10000.

1
0
0
1
0
2
0
3
0
4

n = 16

Key:CurrentMatchSettledEliminated