1, what is Hamming distance
Hamming distance, from the binary aspect, is two equal long string of binary corresponding bit is not the same number of digits, such as
1011
1000//Hamming distance is 2
1100
1010//Hamming distance is 2
2. Algorithm for calculating Hamming distance
idea:
01. After the two given number of different or (^) operations stored in the variable A, Hamming distance is a binary 1 of the number of
02. When a is not 0 o'clock, a bitwise AND (&) operation is performed with the 0x01. If the result is 1, then the statistic variable plus 1
03. Move a right one, repeat step No. 02
Code:
Class Solution {public
:
int hammingdistance (int x, int y) {
int cnt = 0;
X=x^y;
while (x!=0)
{
if (x&0x01)
cnt++;
x=x>>1;
}
return cnt;
}
;
If written in Python, ^ in Python refers to "bitwise XOR": When two corresponding binary differences, the result is 1