Ten problems that drill the bit manipulation tricks from Lesson 21. The whole skill is pattern-matching a prompt to one of a few operators, so these reps pay off fast. Each solution here was actually run and tested.
How to practise. For each problem, first ask which trick fits — XOR to cancel pairs,
x & (x-1)to walk set bits, a mask to pick bits, or 32-bit wraparound with0xFFFFFFFF. Write it, then trace it on the example bit by bit. If a 32-bit problem misbehaves in Python, suspect the missing mask.
The 10 problems
- 1Single Number (LeetCode 136)EasyEvery number appears twice except one: XOR them all, the pairs cancel and the single number is left.arrow_forward
- 2Number of 1 Bits (LeetCode 191)EasyCount the 1 bits in an integer: n & (n - 1) clears the lowest set bit, so count how often until zero.arrow_forward
- 3Counting Bits (LeetCode 338)EasyCount 1 bits for every number 0..n: bits[i] = bits[i >> 1] + (i & 1), reusing a smaller answer.arrow_forward
- 4Reverse Bits (LeetCode 190)EasyReverse the 32 bits of an unsigned integer: shift the result left and pull in n's lowest bit, 32 times.arrow_forward
- 5Missing Number (LeetCode 268)EasyFind the one number missing from 0..n: XOR every index and value, everything pairs up except the gap.arrow_forward
- 6Single Number II (LeetCode 137)MediumEvery number appears three times except one: track each bit's count mod 3 with two masks, ones and twos.arrow_forward
- 7Single Number III (LeetCode 260)MediumTwo numbers appear once, the rest twice: XOR all to get a ^ b, split by its lowest set bit, XOR each group.arrow_forward
- 8Sum of Two Integers (LeetCode 371)MediumAdd two integers without + or -: XOR is the sum without carry, AND shifted left is the carry; repeat.arrow_forward
- 9Bitwise AND of Numbers Range (LeetCode 201)MediumAND of every number in [left, right]: only the shared binary prefix survives, so shift both ends until equal.arrow_forward
- 10Subsets (bitmask enumeration) (LeetCode 78)MediumList every subset of distinct numbers: each integer 0..2^n - 1 is a bitmask that says which items to take.arrow_forward