
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.
1#include <stdio.h>
2
3int hammingDistance(int x, int y) {
4 int xor = x ^ y;
5 int count = 0;
6 while(xor != 0) {
7 count += xor & 1;
8 xor >>= 1;
9 }
10 return count;
11}
12
13int main() {
14 int x = 1, y = 4;
15 printf("%d\n", hammingDistance(x, y));
16 return 0;
17}The XOR operation x ^ y finds differing bits. We then count the set bits in the result by continuously shifting and checking the last bit using xor & 1. Count the number of 1s to get the Hamming distance.