
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.
1function hammingDistance(x, y) {
2 let xor = x ^ y;
3 let count = 0;
4 while (xor !== 0) {
5 count += xor & 1;
6 xor >>= 1;
7 }
8 return count;
9}
10
11console.log(hammingDistance(1, 4));The JavaScript function finds the Hamming distance by calculating the XOR and counting the number of ones in the binary representation.