Bit Manipulation

advanced15 min

Bit Manipulation Overview

Bit manipulation uses AND, OR, XOR, and shifts on integers. Contest problems use it for subsets, parity, and tight state when n is at most about 20.

Common Bitwise Operators

  • AND (&): 1 if both bits are 1
  • OR (|): 1 if at least one bit is 1
  • XOR (^): 1 if bits are different
  • NOT (~): Inverts all bits
  • Left Shift (<<): Shifts bits left
  • Right Shift (>>): Shifts bits right

Bit Tricks Examples

Common Applications

  • Optimization: Fast arithmetic, state compression
  • Masking: Enable/disable bits
  • Subset Generation: Use bits to represent sets
  • Gray Code: Generate binary reflected Gray code
  • Bit DP: Dynamic programming with bitmasks