天天看点

leetcode 461.汉明距离 - 位运算leetcode 461.汉明距离 - 位运算

leetcode 461.汉明距离 - 位运算

题干

两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。

给出两个整数 x 和 y,计算它们之间的汉明距离。

注意:

0 ≤ x, y < 231.

示例:

输入: x = 1, y = 4

输出: 2

解释:

1 (0 0 0 1)

4 (0 1 0 0)

↑ ↑

上面的箭头指出了对应二进制位不同的位置。

知识点&算法

题解

先统计两个数从低到高相异的位数,然后统计剩下的1。

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

还就那个多此一举,直接利用异或的特性,同0异1,先异或再统计1的个数

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

也可以写成

Brian Kernighan 算法:

一个数-1的结果相当于将原数最低位的1置0,其右侧0全置1。因此一个数和其-1的结果做与运算,就可以将原数最低位的1置0。

通过这种方法来统计二进制1的个数。

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