LeetCode/solutions/461. Hamming Distance.md

21 lines
643 B
Markdown
Raw Normal View History

2018-10-30 08:27:24 +00:00
# [461. Hamming Distance](https://leetcode.com/problems/hamming-distance/description/)
# 思路
求海明距离。
先把x和y进行异或^)操作, 再判断异或结果的二进制表示中有多少个1.
计算二进制表示有多少个1可参见这题的题解:[191. Number of 1 Bits](https://github.com/ShusenTang/LeetCode/blob/master/191.%20Number%20of%201%20Bits.md)
。这里采用思路二。
# C++
``` C++
class Solution {
public:
int hammingDistance(int x, int y) {
int res = 0, tmp = x ^ y;
while(tmp > 0){
res ++;
tmp &= (tmp - 1);
}
return res;
}
};
```