
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.
1public class HammingDistance {
2 public static int hammingDistance(int x, int y) {
3 int xor = x ^ y;
4 int count = 0;
5 while (xor != 0) {
6 count += xor & 1;
7 xor >>= 1;
8 }
9 return count;
10 }
11
12 public static void main(String[] args) {
13 int x = 1, y = 4;
14 System.out.println(hammingDistance(x, y));
15 }
16}In this implementation, we calculate x ^ y to find bits that differ and count the number of 1s using a loop to get the Hamming distance.