解题思路:
找对应的二进制位置不相等个数,那么肯定要用到异或的方法,由于int型最多也就32位的二进制,那就从32位开始(也就是正向第一位),一直到最后一位,每一位进行异或,1说明不同,0说明相同,代码如下:
class Solution {
public:
int hammingDistance(int x, int y) {
int count = 0;
// 32位
int i = 31;
while(i --) {
// 加上每一位不相等的次数
count += (x >> i & 1) ^ (y >> i & 1);
}
return count;
}
};
/*作者:heroding
链接:https://leetcode-cn.com/problems/hamming-distance/solution/cyi-huo-by-heroding-hxgr/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/