两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。 给出两个整数 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)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Beginning ARKit for iPhone and iPad
Wallace Wang / Apress / 2018-11-5 / USD 39.99
Explore how to use ARKit to create iOS apps and learn the basics of augmented reality while diving into ARKit specific topics. This book reveals how augmented reality allows you to view the screen on ......一起来看看 《Beginning ARKit for iPhone and iPad》 这本书的介绍吧!