#461

Hamming Distance

Easy XOR + popcount

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Count the bit positions where two integers differ.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: in how many positions do the two numbers' bits differ?

Why this works: XOR leaves a 1 exactly where they differ; count those.

Example: x = 1 (0001), y = 4 (0100)

0001 ^ 0100 = 0101 → two 1s → 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Comparing decimal digits instead of bits.