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;
    }
};

也可以写成

return __builtin_popcount(s);

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值