Maintained by Vikas Dulgunde, software engineer
You are given two non-negative integers, x and y. Write their values in binary and line them up by position. The Hamming distance is the count of positions where one number has a 1 and the other has a 0.
Positions where both bits agree (both 0 or both 1) do not contribute. Only the disagreements are counted, so the answer is always between 0 and the number of bits in the larger value.
Return that count as an integer. The order of the two arguments does not matter, since a position either differs or it does not.
1 is 001 and 4 is 100. The lowest bit and the highest bit disagree, while the middle bit agrees, so two positions differ.
3 is 011 and 1 is 001. Only the middle bit disagrees, so the distance is 1.
15 is 1111 and 0 is 0000. All four of the lowest bits disagree, so the distance is 4.
Visible test cases
Two bits differ exactly when they are not equal. Think about an operation that turns equal bits into 0 and unequal bits into 1.
XOR (x ^ y) produces a number whose set bits mark precisely the positions where x and y disagree. The problem now reduces to counting the set bits of one number.
To count set bits quickly, repeatedly clear the lowest set bit with n & (n - 1) and tally how many times you can do it before reaching 0.
XOR the two numbers so the differing positions become 1s, then walk all bit positions and count how many 1s appear.
After XOR, only the differing bits are set, so counting set bits gives the answer. Clearing the lowest set bit each step runs once per set bit instead of once per position.