461. Hamming Distance

求海明距离,将两个数按位异或,然后计算结果中bit 1的位数即可。其实就是 191. Number of 1 Bits 的问题。

class Solution {
public:
    int hammingDistance(int x, int y) {
        int res=x^y;
        int count=0;
        while (res){
            if (res&1) ++count;
            res >>= 1;
        }
        return count;
    }
};

 

计算二进制数中bit 1的位数,有一种经典的算法,Brian Kernighan's algorithm。

n ^ (n-1) 可以将较低位的1置为0。不同于上面的方法需要对每一位循环,该方法的循环次数等于n中 bit 1的个数。

class Solution {
public:
    int hammingDistance(int x, int y) {
        int res=x^y;
        int count=0;
        while (res){
            ++count;
            res &= res-1;
        }
        return count;
    }
};

 

posted @ 2018-06-06 19:55  約束の空  阅读(104)  评论(0)    收藏  举报