leetcode 461. Hamming Distance

https://leetcode.com/problems/hamming-distance/?tab=Description

两个数字之间的汉明距离就是两个数二进制位对应位不同的个数

按位分别取出两个数对应位的数异或,异或的性质是相同为0, 不同为1,我们把1的情况累加起来就是汉明距离。

int hammingDistance(int x, int y) {
    int xor = x ^ y;
    int count = 0;
    while(xor)
    {
        count += xor & 1;
        xor >>= 1;
    }
    return count;
}

  

posted @ 2017-02-26 12:54  cp_cnblogs  阅读(167)  评论(0编辑  收藏  举报