Eight classic problems, but not eight tricks. They're all built from a handful of moves: read the low bit, drop it, cancel with XOR, delete the lowest 1. Learn the words, not the sentences.
Every "clever" bit trick is a plain sentence once translated. n & 1 asks what's the last
binary digit? n >> 1 says drop it. a ^ b marks where two
numbers differ. n & (n−1) means delete the rightmost 1. Once you read them this
way, bit problems become normal digit-by-digit reasoning — just in base 2.
Type a number, then apply an operation. The register shows the low 16 bits; changed bits flash terracotta and the resulting value is spelled out. This is the whole vocabulary in one place — poke it until each expression reads like plain language.
n & 1) update n; predicates just report.Watch n & (n−1) repeatedly — each press
deletes exactly one 1, so the number of presses to reach zero is the popcount. That's the Hamming-weight
solution, live.
Two equal numbers annihilate: x ^ x = 0. Fold a whole array and every duplicate vanishes,
leaving only the lonely one. That's Single Number in a single line.
n & 1 reads the rightmost bit; n >> 1 peels it off. Reverse Bits,
Counting Bits, trailing zeros — all just decimal-digit reversal, done in binary.
n & (n−1) clears the lowest set bit. Loop until zero and you've counted the ones — the
fastest popcount, and the key to Counting Bits' DP.
XOR is associative and commutative, so order doesn't matter — every value that appears twice cancels to 0, and the accumulator ends holding the unique one. Step through and watch the running XOR.
The accumulator visits ugly intermediate values, but every pair eventually zeroes out. For "every element three times except one," XOR can't help — you count each bit mod 3 instead (tab 3 below).
Each is a short application of the vocabulary. Tap through — the key idea matters far more than the code.
| Expression | Plain meaning |
|---|---|
| n & 1 | Read the lowest bit |
| n >> 1 | Drop the lowest bit (signed shift) |
| n >>> 1 | Drop the lowest bit, fill zero from the left |
| n << 1 | Append a 0 / multiply by 2 |
| a ^ a | 0 — equal values cancel |
| a ^ 0 | a — XOR with zero is identity |
| n & (n − 1) | Remove the lowest set bit |
| n & −n | Isolate the lowest set bit |
| a ^ b | Mark every position where a and b differ |
| 1 << k | A mask with only bit k set |
| (n >> k) & 1 | Read bit k |
| x & (x + 1) == 0 | x is all-ones (000…0111…1) |
n & (n−1) help?
n & (n−1) deletes the lowest set bit.bits[i] = bits[i>>1] + (i&1).