461. Hamming Distance

本文介绍了两种计算两个整数间海明距离的有效方法。一种是通过位运算逐位检查,另一种是利用Brian Kernighan算法减少不必要的循环,提高效率。

求海明距离,将两个数按位异或,然后计算结果中bit 1的位数即可。其实就是 191. Number of 1 Bits 的问题。

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

 

计算二进制数中bit 1的位数,有一种经典的算法,Brian Kernighan's algorithm。

n ^ (n-1) 可以将较低位的1置为0。不同于上面的方法需要对每一位循环,该方法的循环次数等于n中 bit 1的个数。

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

 

转载于:https://www.cnblogs.com/hankunyan/p/9147003.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值