Skip to main content

Bit manipulation

Bitwise operations work directly on binary bits. They are efficient and commonly used for algorithm optimization.

Basic bit operators

Common tricks

1. Check odd or even

2. Swap two numbers without a temporary variable

3. Check whether the k-th bit is 1

4. Set the k-th bit to 1

5. Set the k-th bit to 0

6. Flip the k-th bit

7. Extract the lowest 1 bit

8. Remove the lowest 1 bit

9. Check whether a number is a power of two

10. Count the number of 1 bits in binary

Classic problems

LeetCode 136. Single Number

Problem: every number in the array appears twice except one. Find the one that appears only once. Idea: use the XOR properties a ^ a = 0 and a ^ 0 = a.

LeetCode 191. Number of 1 Bits

LeetCode 231. Power of Two

LeetCode 338. Counting Bits

Typical use cases

  • State compression: represent multiple boolean states with one integer
  • Set operations: implement intersection, union, and complement through bit masks
  • Permission systems: store different permissions as bits
  • Performance optimization: use fast bitwise operations to replace some multiply/divide cases
Last modified on April 17, 2026