-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHammingDistance.cpp
More file actions
52 lines (47 loc) · 870 Bytes
/
HammingDistance.cpp
File metadata and controls
52 lines (47 loc) · 870 Bytes
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
//
//Given two integers x and y, calculate the Hamming distance.
//
//Note:
//0 ¡Ü x, y < 231.
//
//Example:
//
//Input: x = 1, y = 4
//
//Output: 2
//
//Explanation:
//1 (0 0 0 1)
//4 (0 1 0 0)
// ¡ü ¡ü
//
//The above arrows point to positions where the corresponding bits are different.
#include<iostream>
using namespace std;
class HammingDistance
{
public:
int hammingDistance(int x, int y) {
int t = x^y;
int res = 0;
while (t != 0)
{
/*if (t & 1 == 1)
{
++res;
}
t >>= 1;*/
//better one
//turn off the right most bit in n in each iteration
++res;
t &= t - 1;
}
return res;
}
};
void main_HammingDistance(){
HammingDistance hd;
int x = 2, y = 11;
cout<<hd.hammingDistance(x,y)<<endl;
}