Hamming Distance

class Solution {
public:
   int hammingDistance(int x, int y) {
    
    //首先进行异或操作,转成二进制,就是结果中1的个数,为汉明距离
    int tmpInt=x^y;
    int dis=0;
    
    //判断是否为0
    while(tmpInt)
    {
        //如果先右移再左移,结果不一致,证明最低位是1,因为左移总是补0
        if((tmpInt>>1)<<1 != tmpInt)
        {
            //距离加一
            ++dis;
        }
        
        //将右移的结果赋值给tmpInt,注意上面的并没有赋值
        tmpInt>>=1;
    }
    //返回结果
    return dis;
}
};

代码是转载自leetcode的评论,我加了一下中文注释,哈哈哈,在此说明,尊重原创

https://leetcode.com/problems/hamming-distance/discuss/94879/C-simple-solution-0MS

你可能感兴趣的:(LeetCode)