Bit manipulation0/59 done
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 operationO(1)
popcountO(number of set bits)

Reach for it when

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) !== 0

Traps

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.