Bit Manipulation
Treat integers as rows of bits to test and combine flags, apply XOR and lowest-bit identities, and enumerate subsets as bitmasks.
4 objectives 5 steps about 110 min
Check what you know
The lessons are coming later. The knowledge check is ready now.
This skill page is a public outline. Its lessons and knowledge check appear here as subject-matter experts approve them.
Learning objectives
- Use &, |, ^, ~, << and >> to test, set, clear and toggle bits, and explain how Python's unbounded integers represent negative numbers and how to mask a result to a fixed width such as 32 bits.
- Solve problems with bit identities (x & (x - 1), x & -x, XOR cancellation), such as finding the unpaired element, counting set bits, testing for a power of two and finding a missing number, in O(1) extra space.
- Represent flag fields and sets of up to about 20 items as bitmasks: enumerate all subsets and the submasks of a mask, and use a mask as compact state in a search or dynamic programming table.
- Solve aggregate problems one bit position at a time, such as total Hamming distance over all pairs and the element that appears once when every other appears three times, and find the maximum XOR of two numbers with a binary trie.
Lesson plan
5 steps, about 110 min · 0 of 4 lessons available so far
- Integers as Rows of Bits Concept · 20 min · coming later
- XOR and Lowest-Bit Tricks, Derived Worked example · 25 min · coming later
- Lab: Masks as Sets and Flags Lab · 25 min · coming later
- One Bit Position at a Time, and XOR Tries Worked example · 25 min · coming later
- Check: Bitwise Problems Knowledge check · 8 questions
Practise it
Implement single-number, counting set bits for every value from 0 to n, a power-of-two test and 32-bit bit reversal, plus a bitmask subset generator cross-checked against itertools.combinations; pass tests that include negative inputs, zero and the largest 32-bit values. Then compute the total Hamming distance of 10^5 values in O(32n) and the maximum XOR of any pair with a binary trie, checked against brute force on small inputs.
Build it from scratch
Practice builds that exercise this skill by re-creating a real technology.
- Build your own Virtual MachineIntermediate · 6–12 h
References
Hard prerequisites
Unlocks
Nothing depends on this skill yet.
On these roadmaps
Progress and evidence for this skill are shared across all of them.