
Sponsored
Sponsored
To calculate the Hamming distance between two numbers, the most efficient way is to use the XOR operation. The result of XOR operation between two numbers highlights the bits that are different. Once you have the XOR result, the task reduces to counting the number of 1s in the binary representation of this number, which indicates the number of differing bits, thus giving the Hamming distance.
Time Complexity: O(1) since integer size is fixed.
Space Complexity: O(1) because we use a constant amount of space.
1def hammingDistance(x, y):
2 return bin(x ^ y).count('1')
3
4x = 1
5y = 4
6print(hammingDistance(x, y))We use Python's bin() to convert the XOR result to a binary string and count('1') to count differing bits easily.