汉明距离

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

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ xy < 231.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.

解决方案:

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



猜你喜欢

转载自blog.csdn.net/x_shuck/article/details/79404675