mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
21 lines
643 B
Markdown
21 lines
643 B
Markdown
# [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;
|
||
}
|
||
};
|
||
```
|