Builds onBig-O and complexity
01The idea
A computer stores every integer as bits, a row of 0s and 1s. Bit operators work on all the bits of a number at once, so they can replace a loop with one step.
| Operator | Name | What it does to each bit position |
|---|---|---|
a & b | AND | 1 only where both are 1 |
a | b | OR | 1 where either is 1 |
a ^ b | XOR | 1 where they differ |
~a | NOT | flips every bit |
a << k | left shift | moves bits up k places, which multiplies by 2ᵏ |
a >> k | right shift | moves bits down k places, which divides by 2ᵏ |
A handful of tricks cover most problems:
(x >> i) & 1reads bit i.x | (1 << i)sets bit i, andx & ~(1 << i)clears it.x & (x - 1)clears the lowest 1 bit. Subtracting 1 turns that bit into 0 and every 0 below it into 1, so the AND keeps only the bits above it.x & (x - 1) == 0means x is a power of two, for x above 0.x ^ xis 0 andx ^ 0is x. So if every number appears twice except one, XOR-ing them all leaves the one.
A number can also hold a set. With n items, an integer from 0 to 2ⁿ - 1 marks which items are in, one bit per item. That is a bitmask.
02How to spot it
Think about bits when:
- the problem mentions binary, bits, XOR, powers of two or flipping
- every value appears twice except one or two
- the input is small, n up to about 20, and you need to try every subset. Loop a mask from 0 to 2ⁿ - 1
- a DP needs to remember which items are used. Store that set as a mask
Python integers have no fixed size, so ~x is negative and right shifts of negatives keep the sign. Java's int has 32 bits, and >>> shifts without keeping the sign. Use masks such as & 0xFFFFFFFF when the problem expects 32-bit results.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue