Bit Manipulation
Use binary representation and bitwise operators to test, set and clear bits, solve XOR puzzles and enumerate subsets with bitmasks.
Intermediate · about 5 hours · difficulty 3/5
Learn first: Complexity Analysis
Integers are stored in binary, and bitwise operators work on all bits at once in O(1). This enables elegant tricks that interviewers love and that make subset enumeration practical.
Operators and core tricks
- AND
&, OR|, XOR^, NOT~, shifts<<and>>. - Check bit i:
(x >> i) & 1. Set:x | (1 << i). Clear:x & ~(1 << i). Toggle:x ^ (1 << i). x & (x - 1)removes the lowest set bit, sox > 0 && (x & (x - 1)) == 0tests powers of two.x & -xisolates the lowest set bit (used by Fenwick trees).- Count set bits:
__builtin_popcount,Integer.bitCount, orbin(x).count("1").
XOR properties
a ^ a = 0 and a ^ 0 = a, and XOR is commutative. So XOR of all elements cancels pairs, which solves "find the single non-repeated number" in O(1) space. Prefix XOR works just like prefix sums.
Subsets as bitmasks
For n <= 20, every subset of n items is an integer from 0 to 2^n - 1. Loop over masks and check which bits are set to enumerate all subsets. This is the basis of bitmask DP later.
Pitfalls
1 << 40 overflows a 32-bit int; use 1LL << 40 in C++. Operator precedence: x & 1 == 0 parses as x & (1 == 0), so always use parentheses. Right shift of negative numbers is implementation-sensitive in some languages.
Key concepts
- Binary and two's complement
- Get, set, clear, toggle a bit
- x & (x - 1) and x & -x
- XOR tricks: Single Number family
- Counting set bits
- Enumerating subsets with masks
- Iterating submasks of a mask
Mini project
Solve 8 problems: Single Number, Single Number II, Number of 1 Bits, Counting Bits, Power of Two, Missing Number, Subsets (via bitmask), and Minimum Flips to Make a OR b Equal to c.
Check yourself
How does XOR let you find the one element that appears once when every other element appears exactly twice, using O(1) extra space?
Free resources
- Bit manipulation (cp-algorithms)
- Competitive Programmer's Handbook (Ch. 10) (CSES)
- LeetCode Explore (LeetCode)