Codacoda
Back to Academy

bitwise operations

Power of Two Check

A power of two in binary has exactly one set bit (e.g., 8 = 1000). The expression n & (n-1) clears the lowest set bit, so for powers of two it yields zero. Combined with checking n > 0, this gives an O(1) test without division or loops.

Use Cases

  • Memory allocator alignment checks
  • Validating buffer sizes in systems programming
  • Hash table size validation for power-of-two sizing
  • Image dimension validation in graphics processing

Complexity Analysis

MetricBestAverageWorst
TimeO(1)O(1)O(1)
SpaceO(1)

Visualization

Checkn=80000100076543210
Speed:1x
Check if 8 is a power of 2. Powers of 2 have exactly one set bit.Step 1 / 6

Implementation

Output

Click "Run Code" to see output...