Skip to content
ΣDSA Patterns
Menu
Language

Bit Manipulation

Guide 3 of 6 · Path 3 of 6

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

Tested only
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

Bit tricks: lowest-set-bit clear.

Reflection