Bit Manipulation
Use binary operators to check, set and clear bits, solve XOR puzzles and enumerate subsets with masks.
Beginner · about 4 hours · difficulty 2/5
Learn first: Time and Space Complexity
Bit manipulation questions are short and come up often in service-company technical rounds and as OA warm-ups.
Operators and tricks
- AND, OR, XOR, NOT, left and right shifts.
- Check bit i: (n >> i) & 1. Set: n | (1 << i). Clear: n & ~(1 << i). Toggle: n ^ (1 << i).
- n & (n - 1) clears the lowest set bit: power of two check and counting set bits (Brian Kernighan).
- n & (-n) isolates the lowest set bit.
- XOR properties: a ^ a = 0, a ^ 0 = a, order does not matter.
Classic problems
Single Number (XOR all), Single Number II (count bits mod 3), Single Number III (split by a differing bit), Number of 1 Bits, Counting Bits (dp[i] = dp[i >> 1] + (i & 1)), Power of Two, Missing Number, Reverse Bits, Sum of Two Integers without +, Subsets via masks from 0 to 2^n - 1, XOR of numbers from 1 to n (pattern repeats every 4).
Number representation
Know two's complement, why ~n = -n - 1, and that signed right shift copies the sign bit. These come up in viva-style questions.
Pitfalls
- Operator precedence: in C++ and Java, == binds tighter than &, so write (n & 1) == 0 with brackets.
- 1 << 31 overflows a 32-bit int; use 1LL << i for long values.
You are ready to move on when you can solve Single Number III and explain how n & (n - 1) counts set bits.
Key concepts
- Bitwise operators and shifts
- Check, set, clear, toggle a bit
- n & (n - 1) tricks
- XOR properties
- Subsets with bitmasks
- Two's complement
Mini project
Solve these 10 in 5 days, log time and pattern: Number of 1 Bits, Counting Bits, Power of Two, Missing Number, Single Number, Single Number II, Single Number III, Reverse Bits, Subsets (with bitmasks), Sum of Two Integers.
Check yourself
Why does XOR-ing every element of an array find the one element that appears once when all others appear twice?
Free resources
- cp-algorithms: Bit manipulation (cp-algorithms)
- Competitive Programmer's Handbook (Ch. 10) (CSES)
- takeUforward (takeUforward)