LeetCode/solutions/461. Hamming Distance.md

21 lines
643 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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;
}
};
```