Bit Manipulation Bit basics
108. Hamming Distance
You are given two 32-bit signed integers x and y. Their Hamming distance is the number of
positions where their bits differ. Return it.
Compare all 32 bits the way a computer stores the numbers, in two's complement. A non-negative number is its usual binary form with zeros in front. A negative number always has its top bit set: −1 is stored as 32 ones, and −231 is a 1 followed by 31 zeros.
In Python and JavaScript, x and y are ordinary numbers in the same range, and their bits are the same
32 bits.
Example 1
Input: x = 9, y = 14
3Explanation: 9 is 1001 and 14 is 1110. They differ in the three lowest positions and agree in the highest one.
The 28 zeros in front are the same in both.
Example 2
Input: x = -5, y = 5
31Explanation: −5 is stored as 29 ones followed by 011, and 5 is 29 zeros followed by 101. Only the lowest bit
is the same in both.
Example 3
Input: x = 2147483647, y = -2147483648
32Explanation: The largest int is a 0 followed by 31 ones, and the smallest is a 1 followed by 31 zeros. Every bit differs.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
-231 ≤ x, y ≤ 231 − 1
Clarifying questions
What you would ask an interviewer before writing any code.