两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。 给出两个整数 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)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
More Eric Meyer on CSS (Voices That Matter)
Eric A. Meyer / New Riders Press / 2004-04-08 / USD 45.00
Ready to commit to using more CSS on your sites? If you are a hands-on learner who has been toying with CSS and want to experiment with real-world projects that will enable you to see how CSS......一起来看看 《More Eric Meyer on CSS (Voices That Matter)》 这本书的介绍吧!