-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.cpp
54 lines (45 loc) · 1.1 KB
/
main.cpp
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
//==================================================================
// 《Leetcode刷题》代码
// 作者:周涛
//==================================================================
// 面试题:hamming距离计算
// 题目:难点在与每位按位异或之后,怎么计算1的数量
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
#define MAX 100+10
class Solution {
public:
//int hammingDistance(int x, int y) {
// int dist = 0, n = x ^ y;
// while (n) {
// dist++;
// n = n & (n - 1);//与n-1与运算,每一次计算把后面记完数的置零
// }
// return dist;
int hammingDistance(int x, int y) {
int temp = x ^ y;
int dist = 0;
while (temp) {
if ((temp >> 1) << 1 != 0)
dist++;
temp >>= 1;
}
return dist;
}
};
int main()
{
freopen("input.txt", "r", stdin);
int x, y;
Solution s;
int result;
while (scanf("%d %d", &x, &y) != EOF){
result = s.hammingDistance(x, y);
printf("%d\n", result);
}
return 0;
}