-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhamming_distance.cpp
More file actions
57 lines (48 loc) · 947 Bytes
/
hamming_distance.cpp
File metadata and controls
57 lines (48 loc) · 947 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
53
54
55
56
57
// 461. Hamming Distance: https://leetcode.com/problems/hamming-distance
// Author: xianfeng.zhu@gmail.com
#include <stdio.h>
// Iterative loop
class Solution1
{
public:
int hammingDistance(int x, int y)
{
int n = 0;
unsigned int z = x ^ y;
while (z != 0)
{
if (z & 0x01)
{
n++;
}
z >>= 1;
}
return n;
}
};
// Bit manipulation trick
class Solution2
{
public:
int hammingDistance(int x, int y)
{
int n = 0;
unsigned int z = x ^ y;
while (z != 0)
{
n++;
z &= (z - 1);
}
return n;
}
};
using Solution = Solution2;
int main(int argc, char* argv[])
{
int x = 1;
int y = 4;
int n = Solution().hammingDistance(x, y);
printf("Input: x = %d, y = %d\n", x, y);
printf("Output: %d\n", n);
return 0;
}