Chapter 87
HomeBits are fast, compact, and solve problems that look impossible with arithmetic. These tricks appear constantly in competitive programming.
// Check if bit i is set: (x >> i) & 1
// Set bit i: x |= (1 << i)
// Clear bit i: x &= ~(1 << i)
// Toggle bit i: x ^= (1 << i)
// Least significant set bit: x & -x
// Remove LSB: x & (x - 1)
// Count set bits: __builtin_popcount(x) (C++)
// Count set bits: x.count_ones() (Rust)
// Check if power of two:
bool is_pow2(int x) { return x > 0 && !(x & (x - 1)); }
// Get the lowest set bit:
int lsb(int x) { return x & -x; }
// Enumerate subsets of a bitmask:
for (int sub = mask; sub; sub = (sub - 1) & mask) { }x & -x = lowest set bit. x & (x-1) = remove lowest set bit.__builtin_popcount / count_ones = number of 1 bits.for (sub = mask; sub; sub = (sub-1) & mask).