Number Complement

easy

Flip all bits in binary representation

Number Complement

Key Insight

XOR with mask of all 1s (same bit length). Flips all bits.

Step 1Problem
5
5
=
0
0
0
0
0
1
0
1
76543210
101 → ?

Find complement of 5 (101 → 010).

1 / 5

Learn the Pattern

Practice the Code

Step-by-Step Walkthrough: Number Complement

XOR with mask of all 1s (same bit length). Flips all bits.

  1. Problem

    Find complement of 5 (101 → 010).

  2. Find Bit Length

    5 needs 3 bits (101).

  3. Create Mask

    Mask = (1 << 3) - 1 = 7 (111)

  4. XOR with Mask

    5 ^ 7 = 2. Flips all bits!

  5. Result

    Complement of 5 is 2!