汉明距离?

什么是汉明距离?有什么用?

汉明距离是使用在数据传输差错控制编码里面的,汉明距离是一个概念,它表示两个(相同长度)字对应位不同的数量,我们以d(x,y)表示两个字x,y之间的汉明距离。对两个字符串进行异或运算,并统计结果为1的个数,那么这个数就是汉明距离。

汉明距离广泛应用于多个领域。在编码理论中用于错误检测,在信息论中量化字符串之间的差异。

如何计算汉明距离?

法一:通过右移实现1的计数

通过汉明距离的定义可知,就是实现两数异或之后的1的计数。所以至少是要右移32次。

class Solution {
public:
    int hammingDistance(int x, int y) {
        int t = x^y;
        int count = 0;
        for(int i=0;i<32;i++){
            if(t&1==1){
                count++;
            }
            t >>= 1;
        }
        return count;
    }
};

法二:通过消耗1实现计数

二进制数中的1可以如何消耗?很明显11011100-1=11011011。如果将该数与原数相与,可以发现,会把最右边的1消耗掉,这样直接实现了有多少个1就消耗多少次。即通过x&(x-1)来消耗1,最终只要不为0便一直循环计数。

迭代实现

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

递归实现

class Solution {
public:
    int hammingDistance(int x, int y) {
        int t = x^y;
        return solve(t);
    }
private:
    int solve(int t){
        if(!t)
            return 0;
        return solve(t&(t-1))+1;
    }
};

你可能感兴趣的:(Leetcode中级算法,算法,数据分析)