Hamming Distance

Easy

Topics
Bit Manipulation

The Hamming distance between two integers is the number of positions at which the corresponding bits differ. Given integers a and b, return their Hamming distance.

Example 1

3210x = 10001y = 40100x^y0101
The shaded columns are the positions where the two numbers disagree. XOR marks exactly those, so the answer is the number of set bits in x ^ y — 2.
Cells are the binary expansion, most significant bit on the left; the small numbers are bit positions.
Input:  a = 1, b = 4
Output: 2
Explanation: 0001 vs 0100 differ in two bits.

Example 2

3210x = 30011y = 10001x^y0010
Input:  a = 3, b = 1
Output: 1

Constraints

  • 0 <= a, b <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

The Hamming distance counts bit positions where two numbers differ. x XOR y sets exactly those bits — XOR is 1 when its inputs disagree — so the problem reduces to counting the 1-bits of a single number.

Counting set bits can be a loop over all 32 positions, or the faster n & (n-1) trick, which clears the lowest set bit each time and so iterates once per set bit rather than once per position. 💡 Subtracting 1 flips the lowest set bit to 0 and everything below it to 1, so ANDing removes exactly that bit.

Approach

  1. Compute x XOR y.
  2. Count its set bits, via a builtin popcount or while v: v &= v - 1; count += 1.

Dry Run

x = 1, y = 4

  1 = 0001
  4 = 0100
XOR = 0101   -> two bits set

count with v &= v-1:
  v = 0101, v-1 = 0100, AND -> 0100   count 1
  v = 0100, v-1 = 0011, AND -> 0000   count 2
  v = 0, stop

answer 2

Complexity

  • Time — O(1): the inputs are fixed-width, so at most 32 iterations, and with the n & (n-1) trick only as many as there are set bits.
  • Space — O(1).

Common Pitfalls

  • Comparing decimal digits rather than bits.
  • Using a signed right shift in a loop over a negative XOR result, which sign-extends and never terminates. Not reachable here since the constraints are non-negative, but it is the classic bug in this family — use an unsigned shift or the n & (n-1) form.
  • Reimplementing popcount when the language has one: Integer.bitCount, __builtin_popcount, bin(v).count("1").
  • Assuming both numbers have the same bit length. XOR handles differing magnitudes without alignment work.

Full Solution — all languages

class Solution:
    def hammingDistance(self, a, b):
        return bin(a ^ b).count('1')
SensAI
Beta
Tap the mic to stop voice mode