Hamming Distance

easy

Count differing bit positions between two numbers

Hamming Distance

Key Insight

XOR gives 1s where bits differ. Count the 1s in the XOR result.

Step 1Problem
1
1
=
0
0
0
0
0
0
0
1
4
4
=
0
0
0
0
0
1
0
0
76543210
001 vs 100

Hamming distance between 1 and 4.

1 / 5

Learn the Pattern

Practice the Code

Step-by-Step Walkthrough: Hamming Distance

XOR gives 1s where bits differ. Count the 1s in the XOR result.

  1. Problem

    Hamming distance between 1 and 4.

  2. XOR

    1 ^ 4 = 5. 1s show differing positions.

  3. Count 1s

    5 = 101 has two 1-bits.

  4. Use n & (n-1)

    5 & 4 = 4, 4 & 3 = 0. Count = 2.

  5. Result

    Hamming distance = 2