Check if a number is a power of two using bit manipulation: n & (n-1) == 0
n - 1: single CPU instructionn & (n-1): single CPU instructionPowers of two have exactly one bit set: 2k = 1 followed by k zeros. Subtracting 1 flips all bits from the rightmost set bit down: n - 1 changes 100...0 to 011...1. The AND of these shares no common bits, yielding zero. For non-powers, at least one higher bit survives.
The operation n & (n-1) clears the rightmost set bit. This technique is foundational in bit manipulation (e.g., counting set bits, finding lowest set bit).
n - 1: one registerBit manipulation operates on fixed-width integers (32 or 64 bits). The space used is independent of the numeric value—a 64-bit integer uses 8 bytes whether it holds 1 or 263. No auxiliary data structures are needed.
Alternative approaches (loop counting bits, division by 2) use O(log n) time. The bit trick achieves O(1) by exploiting binary representation properties.