371/670

371. Hamming Distance

Easy

The Hamming distance between two integers is the number of bit positions at which their binary representations disagree.

Given two non-negative integers x and y, return their Hamming distance — how many bits you would have to flip to turn one into the other.

Where 1 and 4 disagreeStacking the binary forms of 1 (001) and 4 (100): bits 2 and 0 disagree while bit 1 matches, so the Hamming distance is 2.
x = 1001y = 4100=2 positions differ → distance 2bit 2bit 1bit 0

Example 1:

Input: x = 1, y = 4

Output: 2

Explanation: In binary, 1 is 001 and 4 is 100. Bits 0 and 2 disagree, so the distance is 2.

Example 2:

Input: x = 3, y = 1

Output: 1

Explanation: 3 is 11 and 1 is 01. Only bit 1 differs.

Constraints:

  • 0 ≤ x, y ≤ 2³¹ - 1

Hints:

XOR is the disagreement detector: a bit of x ^ y is 1 exactly where x and y differ. The answer is the number of 1-bits in x ^ y.

To count 1-bits without checking all 32 positions, use z & (z - 1): it clears the lowest set bit, so the loop runs once per set bit.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: x = 1, y = 4

Expected output: 2