Bits basics
Every whole number is stored as a row of bits, each worth a power of two. A few operators work on all those bits at once: AND, OR, XOR, NOT and the shifts. Knowing what each does to one bit, plus the trick n & (n - 1), answers most questions about powers of two, positions of bits, and multiplying or dividing without * or /.
How to recognise it
- The question mentions bits, binary, powers of two, or doing arithmetic without *, / or %.
- A value can be described by which of its bits are 1.
- Limits are given as 32-bit integers, and overflow matters.
The idea in one picture
Write 13 in binary: 1101. Read from the right, the bits are worth 1, 2, 4 and 8, and 13 = 8 + 4 + 1. Bit operators work
on every column at once, like adding in columns but without carries.
| Operator | Rule for one bit | Example (12 is 1100, 10 is 1010) |
|---|---|---|
a & b (AND) | 1 only if both are 1 | 1000 = 8 |
a | b (OR) | 1 if either is 1 | 1110 = 14 |
a ^ b (XOR) | 1 if they differ | 0110 = 6 |
~a (NOT) | flips every bit | ~12 = -13 in two's complement |
a << k | shifts left, filling with 0 | 12 << 1 = 24 |
a >> k | shifts right | 12 >> 2 = 3 |
Tricks worth knowing by heart
| Expression | Meaning |
|---|---|
(n >> i) & 1 | bit i of n (0 or 1) |
n & (n - 1) | n with its lowest set bit cleared |
n & -n | only the lowest set bit of n |
n << k, n >> k | n × 2^k, n / 2^k (rounded down for non-negative n) |
Arithmetic with shifts
A product a × b is the sum of a << i over the set bits i of b. A quotient a / b is found from the top bit down:
if b << i still fits into what is left of a, subtract it and set bit i of the answer. This is long division in
base 2.
Common mistakes
- Forgetting that operator precedence puts
&below==in Java and C++: write(n & 1) == 1, notn & 1 == 1. - Shifting a 32-bit
1by 31 or more, which overflows; use1Lor1LLfor wide shifts. - Treating negative numbers like positive ones:
~nand>>behave differently on them.
Problems
- Power of Twoeasyguide ready
- Find position of the only set biteasyguide ready
- Calculate square of a number without using *, / and pow()easyguide ready
- Divide Two Integersmediumguide ready