Part 1 · Concepts · Bits
Bit manipulation
Treat a number as a row of 0s and 1s. Fast tricks for flags, counting and pairing.
How it works
n & (n - 1) clears the lowest set bit, so a power of two (one bit) becomes 0, and repeating it counts bits. a ^ a = 0 and a ^ 0 = a, so XOR of everything cancels pairs. Flags: OR to set, AND to test, AND NOT to clear.
| each operation | O(1) |
| popcount | O(number of set bits) |
Reach for it when
- Single number among pairs
- Power of two checks
- Permission or feature flags in one integer
- Subsets as bitmasks for small n
Implementation (JavaScript, tested)
const isPowerOfTwo = n => n > 0 && (n & (n - 1)) === 0; // one bit set
function popcount(n) {
let c = 0;
while (n) {
n &= n - 1;
c++;
}
return c;
} // drop lowest bit
const singleNumber = nums => nums.reduce((x, n) => x ^ n, 0); // pairs cancel: a ^ a = 0
// Flags: const READ = 1, WRITE = 2, ADMIN = 4; perms |= WRITE; (perms & ADMIN) !== 0Traps
- JS bitwise operators work on 32-bit signed ints. Big numbers break; use BigInt.
- >> keeps the sign, >>> fills with zeros.
In real systems: Unix file permissions (chmod 755), feature flag masks, Bloom filters, Redis bitmaps (SETBIT) for daily active users.
Say out loud: XOR cancels pairs, so whatever's left appears once. O(n) time, O(1) space.