Set, clear, flip
Change single bits of a number with masks. About 9 minutes.
A mask points at one bit
A mask is a number with only the bit you care about switched on, like a stencil with a single hole. Shifting 1 left by k places gives a 1 followed by k zeros, so exactly bit k is on.
Combine the number with the stencil: OR switches that bit on, AND with the flipped stencil switches it off, and XOR flips it. Every other bit is left alone.
mask = 1 << k n | mask # set bit k n & ~mask # clear bit k n ^ mask # toggle bit k
- n
- 8
set 3: mask = 1 << 3 = 1000. n | mask turns bit 3 on. n = 8.
Bits as switches
Real programs pack many on/off flags into one number this way: file permissions, which items are chosen, which cells are visited. A single 32-bit number holds 32 switches in just four bytes.
You will use exactly this idea in the next step to stand for subsets.
for op in ops:
word, k = op.split()
mask = 1 << int(k)
if word == "set":
n |= mask
elif word == "clear":
n &= ~mask
else:
n ^= mask
return nn = 5 (101). What is n after toggling bit 1?
- A7
- B4
- C5
Show the answer
7. Bit 1 was 0; ^ 2 turns it on: 111 = 7.
Apply bit operations
Start with n and apply each operation in order. Each is "set k", "clear k" or "toggle k", acting on bit k (bit 0 is the lowest). Return the final number.
n = 0, ops = ["set 3", "toggle 0", "clear 3"] → 1
0 ≤ n ≤ 2^30 · 0 ≤ ops ≤ 1,000 · 0 ≤ k ≤ 29