461. Hamming Distance

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 ≤ x, y < 231.

思路:即二进制化之后对应位上不同的位的数目,所以将两个数相异或之后得到的数,该数二进制化后为1 的位的个数即汉明距离。

知识点:

1.异或操作:x^y

2.统计一个数二进制后为1的位的数目

代码1:

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

代码2:

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

代码3:

class Solution {
public:
    int hammingDistance(int x, int y) {
        bitset<32> xBS(x);
        bitset<32> yBS(y);
        int count = 0;
        for(int i = 0; i < 32; i++)
        {
            if(xBS[i] != yBS[i])
            {
                count++;
            }
        }
        return abs(count);
    }
};
bitset 用于处理二进制位集。是一种类模板,头文件为 <bitset>  ,如何使用作了解。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值