EasyBitwise Manipulation

Hamming Distance

Explanation & Solution

Description

The [Hamming distance](https://en.wikipedia.org/wiki/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.

Input: x = 1, y = 4

Output: 2

Explanation:

`

1 (0 0 0 1)

4 (0 1 0 0)

↑ ↑

`

The two positions marked with have different bits.

Constraints

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

Approach

Bitwise Manipulation pattern

Key Insight

  • XOR naturally highlights where two values differ bit by bit
  • Counting those bits gives the Hamming distance
  • Time: O(1) for 32-bit integers | Space: O(1)

Solution Code