Learner Level

Implement the hammingDistanceValues method that returns the number of bit positions where two integers differ.

The input contains two integers, x and y.

Your task is to return the Hamming distance between them. The Hamming distance is the number of bit positions where the binary representations of the two numbers are different.

For example, 1 is binary 001 and 4 is binary 100. They differ in two positions, so the answer is 2.

Example 1

Input
x (int) = 1
y (int) = 4
Returns (int) 2

Example 2

Input
x (int) = 3
y (int) = 1
Returns (int) 1

Example 3

Input
x (int) = 0
y (int) = 0
Returns (int) 0

Use XOR to find the positions where the bits are different.

For each bit position, XOR gives 1 when the bits are different and 0 when they are the same. So the problem becomes counting how many set bits are present in x XOR y.

Count the set bits by repeatedly checking the last bit and shifting the value to the right.

Pseudocode:

function hammingDistanceValues(x, y):
    value = x XOR y
    count = 0
    while value > 0:
        if value % 2 == 1:
            count++
        value = value / 2
    return count
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.