Community Problem

Hamming Distance

Difficulty: Easy

Count the bit positions where two non-negative integers differ using XOR plus a population-count loop.

Hamming Distance

Count the bit positions where two non-negative integers differ using XOR plus a population-count loop.

EASY
Free
bit-manipulation
math
freyadiallo

By @freyadiallo

May 17, 2026

·

Updated May 18, 2026

870 views

25

4.2 (12)

I had this on a Cisco networking team interview, where they cared about the answer because the same trick shows up in error-correcting codes. Two operations only: XOR the inputs to mark differing bits, then popcount the result. The interviewer was specifically NOT looking for a 32-iteration loop checking each bit; they wanted Brian Kernighan's trick that runs in time proportional to the number of set bits.

Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, return the Hamming distance between them.

Examples

Example 1:

  • Input: x = 1, y = 4
  • Output: 2
  • Explanation: 1 = 0001, 4 = 0100. Two bits differ.

Example 2:

  • Input: x = 3, y = 1
  • Output: 1
  • Explanation: 3 = 011, 1 = 001. One bit differs.

Example 3:

  • Input: x = 0, y = 0
  • Output: 0
  • Explanation: Identical inputs differ in zero bits.

Example 4:

  • Input: x = 0, y = 2147483647
  • Output: 31
  • Explanation: 0 vs 0x7FFFFFFF differs in 31 bits.

Constraints

  • 0 <= x, y <= 2^31 - 1.

Follow-up

Why XOR? (x ^ y) has a 1 in every position where x and y differ, so the Hamming distance equals the number of set bits in the XOR. Brian Kernighan's n &= n - 1 clears the lowest set bit per iteration, giving O(popcount) instead of O(32).

Solution

Hints

0/3
Hint 1
Hint 2
Hint 3
All Problems