[LeetCode] 汉明距离

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

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

注意:
0 ≤ x, y < 231.

示例:

输入: x = 1, y = 4

输出: 2

解释:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

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

方法一:直接通过^操作和&操作计算两个数每一位是否相同

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

方法二:假如数为num, num & (num - 1)可以快速地移除最右边的bit 1, 一直循环到num为0, 总的循环数就是num中bit 1的个数。来源:https://www.cnblogs.com/grandyang/p/6201215.html

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

猜你喜欢

转载自blog.csdn.net/weixin_37992828/article/details/82731492