Bit manipulation problems have a reputation for feeling like party tricks — clever one-liners that either occur to you instantly or don’t occur to you at all.
That reputation is partly earned, but the tricks themselves come from a small, learnable set of properties of the AND, OR, XOR, and shift operators, and once those properties are second nature, “clever” starts to feel more like “mechanical.” this article covers the handful of identities that show up again and again: clearing the lowest set bit, using XOR’s self-canceling property to find an unpaired value, and using shifts to reason about ranges of numbers at once.
The signal for reaching for bit manipulation is usually explicit: a problem that talks about numbers “appearing twice” except for one or two outliers, a problem asking whether a number is a power of two (or four, or any other power), a problem that wants a running count of set bits, or a problem framed around flags, masks, or binary representations directly. A subtler signal is a constraint that numbers fit in a fixed-width integer with an expected O(1)-extra-space solution — that often means the intended trick lives at the bit level rather than in an auxiliary hash set. Bit tricks are the wrong lens when a problem is fundamentally about relationships that don’t reduce to parity or masking; forcing one onto an ordinary array or graph problem just produces harder-to-read code for no benefit.
Two properties do almost all the work in this article. First, n & (n - 1) always clears the single lowest set bit of n — subtracting one flips every trailing zero to a one and the lowest one to a zero, so ANDing with the original clears exactly that bit and leaves everything above it untouched. Second, XOR is both commutative and its own inverse: a ^ a == 0 and a ^ 0 == a for any a, which means that XOR-ing a whole collection of numbers together cancels out every value that appears an even number of times, leaving only what appears an odd number of times. Everything in this article is a variation on one of those two ideas, plus ordinary shift arithmetic for reasoning about ranges.
Continue with the book
Explore the full treatment, worked examples, and exercises in Algorithmic Edge.
Companion article for Algorithmic Edge, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.
