Skip to content
DeepForgeby svx
All problems
EasyAlgorithmsal-140

Hamming Distance

Problem

Return the number of bit positions at which the non-negative integers x and y differ.

XOR the two values so differing bits become 1, then count the set bits with n = n & (n - 1). Equal values give 0.

Hint

Hamming distance is exactly the popcount of the XOR.

Test cases

case 1
in: [1,4]
expected: 2
case 2
in: [3,1]
expected: 1
case 3
in: [0,0]
expected: 0
case 4
in: [255,0]
expected: 8
case 5
in: [5,5]
expected: 0
Starter codePython
def hamming_distance(x, y):
    # Your code here
    pass

5 test cases · run your code against them in the editor