oneby7

Bit Manipulation Bit basics

108. Hamming Distance

Easy

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

Output: 3

Explanation: 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

Output: 31

Explanation: −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

Output: 32

Explanation: 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.

x = 3, y = 10

Constraints

  • -231 ≤ x, y ≤ 231 − 1

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.