Bit manipulation is a technique for solving problems efficiently using bitwise operations. It is useful for optimization and low-level programming tasks.
In Competitive Programming (CP), bit manipulation is a “superpower.” It allows you to solve problems in $O(1)$ or $O(K)$ (where $K$ is the number of bits, usually 30 or 60) that would otherwise take $O(N)$ loops.
Computers store integers as sequences of bits (0s and 1s).
int (up to $\approx 2 \times 10^9$)long long (up to $\approx 9 \times 10^{18}$)| Operator | Symbol | Mnemonic | Logic |
|---|---|---|---|
| AND | & |
“Both must be 1” | $1 \& 1 = 1$, else $0$ |
| OR | \| |
“At least one 1” | $0 \mid 0 = 0$, else $1$ |
| XOR | ^ |
“Must be different” | $1 \oplus 0 = 1$, $0 \oplus 1 = 1$, else $0$ |
| NOT | ~ |
“Flip everything” | $\sim 1 = 0$, $\sim 0 = 1$ |
| Left Shift | << |
“Multiply by 2” | $a \ll b$ means $a \times 2^{b}$ |
| Right Shift | >> |
“Divide by 2” | $a \gg b$ means $a / 2^{b}$ |
^)XOR is the most important bitwise operator in competitive programming.
Key Properties:
Classic Problem:
These are standard patterns you will use in almost every bitwise problem.
How do I know if the $i$-th bit is set (1) or unset (0)?
bool isSet = (n & (1 << i)) != 0;
How do I turn the $i$-th bit ON?
n = n | (1 << i);
How do I turn the $i$-th bit OFF?
n = n & ~(1 << i);
How do I flip the $i$-th bit ($0 \to 1$, $1 \to 0$)?
n = n ^ (1 << i);
Checking $n \% 2$ is slow. Checking the last bit is fast.
if (n & 1) { /* It's Odd */ }
else { /* It's Even */ }
A power of 2 (like 2, 4, 8, 16) has exactly one bit set.
bool isPowerOfTwo = (n > 0) && ((n & (n - 1)) == 0);
C++ has extremely fast built-in functions for counting bits. Use these instead of writing loops.
| Function | Description | Example $x = 5$ ($101$) | Returns |
|---|---|---|---|
__builtin_popcount(x) |
Count number of 1s | $101$ | $2$ |
__builtin_clz(x) |
Count Leading Zeros | $101$ (32-bit int) | $29$ |
__builtin_ctz(x) |
Count Trailing Zeros | $101$ | $0$ |
Important Note: For long long, append ll (e.g., __builtin_popcountll(x)).
Let’s try a quick mental exercise to verify your understanding.
Problem: You have the number $n = 5$ (binary $101$).
Think about it, then scroll down for the answer.