Command Palette

Search for a command to run...

Module 34

Bit Manipulation

Work directly on binary: the six operators, two's complement, XOR tricks, masks, counting bits and adding without +.

Intermediate 3 lessons 10 problems ~35 min of lessons

Every int in Java is 32 bits. Bit manipulation reads and changes those bits directly with &, |, ^, ~, << and >>. It turns some problems into one-liners (is n a power of two?), finds the odd one out with no extra memory, and lets an int act as a set of up to 32 flags, which is what bitmask DP (Module 32) is built on.

This module explains binary and two's complement, the operators and their traps, the standard tricks (lowest set bit, clear lowest bit, test/set/clear bit i), XOR identities, and a set of classic problems.

Best after: Java for DSA

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. XOR cancels pairs in O(1) space.

  2. Brian Kernighan's loop: n & (n − 1) removes one set bit per step.

  3. A DP over numbers: bits(i) = bits(i >> 1) + (i & 1).

  4. A power of two has exactly one set bit.

  5. Build a result bit by bit with shifts, treating the int as 32 unsigned bits.

  6. Count each bit position modulo 3.

  7. Split by one differing bit to isolate two singles.

  8. Addition as XOR (sum without carry) plus AND-shift (the carries), repeated.

  9. A 26-bit mask per word turns "no common letters" into one AND.

  10. The AND of a range keeps only the common binary prefix of its ends.