
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.
1using System;
2
3class HammingDistance {
4 public static int Calculate(int x, int y) {
5 int xor = x ^ y;
6 int count = 0;
7 while (xor != 0) {
8 count += xor & 1;
9 xor >>= 1;
10 }
11 return count;
12 }
13
14 static void Main() {
15 int x = 1, y = 4;
16 Console.WriteLine(Calculate(x, y));
17 }
18}The code calculates Hamming distance by XOR-ing the numbers and counting bits set to 1 in the result by iterating over each bit.