Skip to content
Problem 461 · LeetCode 461(opens in a new tab)

Hamming Distance

EasyBit manipulation

You are given two non-negative whole numbers, x and y. Write both in binary, lined up by position. Count the positions where one number has a 0 and the other has a 1.

That count is called the Hamming distance between x and y. Return it.

Example 1

Input:  x = 6, y = 13
Output: 3
Why:    0110 and 1101 differ at bits 0, 1 and 3
2 more examples and the constraints

Example 2

Input:  x = 9, y = 8
Output: 1
Why:    1001 and 1000 differ only at bit 0

Example 3

Input:  x = 25, y = 25
Output: 0
Why:    equal numbers have no differing bits

Constraints

  • 0 ≤ x, y ≤ 2,147,483,647 (that is, 2³¹ − 1)

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Compare bit by bitO(31)
  2. XOR, then count the 1sO(k)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeLoop rounds for x = 9, y = 8Verdict
Compare bit by bitO(31)
Passes; always 31 rounds
XOR, then count the 1sO(k)
Best; one round per difference

k = how many bit positions differ between x and y.

Edge cases to test

  • Equal numbers. x ^ y is 0, so the loop never runs and the answer is 0.
  • One of them is 0. The distance is the number of 1 bits in the other one.
  • The largest inputs. 0 and 2,147,483,647 differ in all 31 low bits: the worst case.
  • Different lengths. 25 is 11001 but 3 is 11. Comparing by position with shifts or XOR never needs padding; comparing strings does.

Common mistakes

  • Comparing the binary strings character by character without padding them to the same length first.
  • Using AND or OR instead of XOR: only XOR marks the positions that differ.
  • Writing diff & diff - 1 without checking how the language orders & and -.

How to talk through it

  1. 1Clarify. Are both numbers non-negative? Do they fit in 32 bits?
  2. 2Give the simple loop. Compare bit i of each number for every position and count the mismatches.
  3. 3Name the shortcut. XOR is 1 exactly where two bits differ, so the question becomes: how many 1s does x ^ y have?
  4. 4Count the 1s fast. diff & (diff − 1) drops the lowest 1, so the loop runs once per difference.
  5. 5Test out loud. Run equal numbers, a 0 and the largest value before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?