LeetCode 461. Hamming Distance (C++)

本文介绍了一种计算两个整数间汉明距离的方法,通过对比二进制位的不同来计算距离,详细解析了算法思路并提供了C++实现代码。

题目:

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 < 2^31.

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.

分析:

将两个数的二进制进行比较,不同的计数加一,最后返回总数。

由于1&1 = 1,1&0 = 0,可以分别将x,y和1做与运算得到x,y的最后一位的值,再做异或运算,然后再将x,y右移一位。因为题里限定了x,y大小,所以只32次循环就够了。

程序:

class Solution {
public:
    int hammingDistance(int x, int y) {
        int nums = 0;
        for (int i = 0; i < 32; i++){
            if ((x & 1) ^ (y & 1))
                nums++;
            x = x >> 1;
            y = y >> 1;
        }
        return nums;
    }
};

转载于:https://www.cnblogs.com/silentteller/p/10705303.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值