64. Hamming Distance (Hamming Distance)

Source: Internet
Author: User

[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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.