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
| Metric | Best | Average | Worst |
|---|---|---|---|
| Time | O(1) | O(1) | O(1) |
| Space | O(1) | ||
Visualization
Implementation
Output
Click "Run Code" to see output...