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)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Introduction to Algorithms, 3rd Edition

Introduction to Algorithms, 3rd Edition

Thomas H. Cormen、Charles E. Leiserson、Ronald L. Rivest、Clifford Stein / The MIT Press / 2009-7-31 / USD 94.00

Some books on algorithms are rigorous but incomplete; others cover masses of material but lack rigor. Introduction to Algorithms uniquely combines rigor and comprehensiveness. The book covers a broad ......一起来看看 《Introduction to Algorithms, 3rd Edition》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具