DSA Master › Topic 17
Bit Manipulation
Bit tricks give O(1) space answers to some problems. XOR cancels matching pairs, x & (x − 1) clears the lowest set bit, and shifts let you read or set individual bits.
Concepts
- XOR
- AND / OR
- Shifts
- Bit masks
- Bit counting
How to recognise it
- Every element appears twice except one. XOR them all.
- You need to count set bits, reverse bits, or do arithmetic without + and −.
- Subsets of a small set can be stored as a bitmask.
Common pitfalls
- Java has no unsigned int. Use >>> for a logical right shift.
- Counting Bits: bits[i] = bits[i >> 1] + (i & 1).
Problems
- Single Number (Easy)
- Number of 1 Bits (Easy)
- Counting Bits (Easy)
- Reverse Bits (Easy)
- Sum of Two Integers (Medium)