Hamming Distance

本文介绍了如何计算两个整数之间的汉明距离,并提供了C++和Python两种语言的实现方法。汉明距离是指两个字符串对应位置的不同字符的数目,在计算两个整数的汉明距离时,可以通过异或操作得到两个整数的二进制表示中不同的位数。

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.

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变成0

//C++
class Solution {
public:
    int hammingDistance(int x, int y) {
        int dist = 0;
        int n = x ^ y;
        while(n){
            ++dist;
            n &= n-1;
        }
        return dist;
    }
};

另外python中内置bin函数可以将整数转换为二进制字符串,然后用count函数统计字符串中1的个数也可以达到效果

#python
class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        return bin(x^y).count('1')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值