Bits: tiny yes-or-no switches
Picture
Bits 101 mean switches A and C are on while B is off.
Predict
What does x & (1 << i) test?
Walk through the small example
Whether bit i is set. Independent yes/no facts map naturally to bit positions.
Mental model and complete Python solution
A bit is a labeled switch. The integer is merely the board holding those switches. Say what each position means before performing clever arithmetic.
What the function promises: Return mask membership, insertion, removal, and toggle results for a nonnegative mask and index.
def has_bit(mask, index): return bool(mask & (1 << index))
def add_bit(mask, index): return mask | (1 << index)
def remove_bit(mask, index): return mask & ~(1 << index)
def toggle_bit(mask, index): return mask ^ (1 << index)
mask = add_bit(0, 2)
assert has_bit(mask, 2) and not has_bit(mask, 1)
assert remove_bit(mask, 2) == 0
assert toggle_bit(toggle_bit(0, 4), 4) == 0
Work and storage: Each operation is O(1) in the fixed-machine-word model; arbitrary-precision Python cost grows with bit length.
When to recognize it: Independent yes/no facts map naturally to bit positions.
Check before applying it: Compact storage does not reduce the 2^n number of possible masks, and signed-width assumptions vary by language.
Change one rule
Need the number of set bits.
See what changes
Use int.bit_count(), or repeatedly clear the lowest set bit with x &= x−1.
Connect
bitmasks: Turn these operations into subset-state representation.
XOR: remember odd occurrences: XOR cancellation exposes parity of occurrences.