Algorithm – calculates the hamming distance
1. The subject
Given two integers x and y, calculate the hamming distance between them.
Hamming distance
Hamming distance is a concept used in data transmission error control coding. It refers to two words (of the same length) corresponding to different numbers of bits. We refer to the Hamming distance between two words x and y as D (x,y). XOR is performed on two strings and the number of ones is counted. This number is the hamming distance.
Example:
- Enter: x = 1, y = 8
- Output: 2
-
Explanation:
- (0 0 0 1)
-
(1 0 0 0) ↑
The arrows above indicate the different positions of the corresponding binary bits.
Code 2.
2.1. C
public class Solution { public int HammingDistance(int x, int y) { var n = x ^ y; // Counting the number of 1 var counter = 0; while(n>0){ n = n & (n-1); counter ++; } return counter; }}
Javascript 2.2.
var hammingDistance = function(x, y) {
let n = x^y;
let counter = 0;
while(n){
counter ++;
n = n & (n-1);
}
return counter;
};
3. Also: count the number of 1 in the binary digit
Subtracting 1 from an integer and summing with the original integer turns the rightmost 1 into a 0. Thus, this operation can be performed as many times as there are ones in the binary of an integer.
let counter = 0;
while(n){
counter ++;
n = n & (n-1);
}