Number Complement
easyFlip 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
Flip all bits in binary representation
XOR with mask of all 1s (same bit length). Flips all bits.
Find complement of 5 (101 → 010).
XOR with mask of all 1s (same bit length). Flips all bits.
Find complement of 5 (101 → 010).
5 needs 3 bits (101).
Mask = (1 << 3) - 1 = 7 (111)
5 ^ 7 = 2. Flips all bits!
Complement of 5 is 2!