LeetCode每日一题: 汉明距离(No.461)

栏目: 编程工具 · 发布时间: 6年前

两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。
给出两个整数 x  y,计算它们之间的汉明距离。
复制代码

示例:

输入: x = 1, y = 4
 输出: 2

 解释:
 1   (0 0 0 1)
 4   (0 1 0 0)
           
上面的箭头指出了对应二进制位不同的位置。
复制代码

思考:

通用异或运算,相同为1不同为0,计算x异或y
然后计算结果中1的个数,即为不同的位置数目,即为汉明距离。
复制代码

实现:

class Solution {
    public int hammingDistance(int x, int y) {
       return  hammingWeight(x^y);
    }
    public int hammingWeight(int n) {
        int count = 0;
        while(n != 0) {
            n = n & (n-1);
            count++;
        }
        return count;
    }
}复制代码

以上所述就是小编给大家介绍的《LeetCode每日一题: 汉明距离(No.461)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Distributed Algorithms: An Intuitive Approach

Distributed Algorithms: An Intuitive Approach

Wan Fokkink / MIT Press / 2018-2-2 / USD 48.00

The new edition of a guide to distributed algorithms that emphasizes examples and exercises rather than the intricacies of mathematical models. This book offers students and researchers a guide to ......一起来看看 《Distributed Algorithms: An Intuitive Approach》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

MD5 加密
MD5 加密

MD5 加密工具