The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note: 0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different. AC代码如下:
class Solution {
public:
int hammingDistance(int x, int y) {
int xorRet=x^y;//异或结果的1的个数即为不相同的数量
int count=0;
while(xorRet){
xorRet=xorRet&(xorRet-1);
count++;
}
return count;
}
};
转载请注明原文地址: https://ju.6miu.com/read-670252.html