[Link to this article]
Http://www.cnblogs.com/hellogiser/p/hamming-distance.html
【Introduction]
In the information field,Two strings of equal lengthThe Hamming distance of is the number of different characters at the same position, that is, the number of times to replace a string with another string.
For example:
XxxxyyAndXxxxzzThe Hamming distance of is 2;
111100And111111The Hamming distance of is 2;
For binary numbers, the result of the Hamming distance is equivalent to the number of 1 in the result of a ^ B.
[String]
C ++ Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
/* Version: 1.0 Author: hellogiser Blog: http://www.cnblogs.com/hellogiser Date: */ // Hamming distance of two strings Unsigned hamdist (const char * str1, const char * str2) { // Aaabb aaacc If (str1 = NULL | str2 = NULL) Return 0;
Int len1 = strlen (str1 ); Int len2 = strlen (str2 ); If (len1! = Len2) Return 0;
Unsigned dist = 0; While (* str1 & * str2) { Dist + = (* str1! = * Str2 )? 1: 0; Str1 ++; Str2 ++; } Return dist; }
|
[Number]
C ++ Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
/* Version: 1.0 Author: hellogiser Blog: http://www.cnblogs.com/hellogiser Date: */ // Hamming distance of two integer 0-1 bits Unsigned hamdist (unsigned x, unsigned y) { // 11111 11100 Unsigned dist = 0, val = x ^ y; // XOR
// Count the number of set bits While (val) { ++ Dist; Val & = val-1; }
Return dist; } |
[Reference]
Http://blog.csdn.net/fuyangchang/article/details/5637464
Http://en.wikipedia.org/wiki/Hamming_distance
Http://my.oschina.net/u/1401481/blog/223223
[Link to this article]
Http://www.cnblogs.com/hellogiser/p/hamming-distance.html