The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, return the Hamming distance between them.
示例
示例 1:
输入:x = 1, y = 4
输出:2
解释:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
上面的箭头指出了对应二进制位不同的位置。
示例 2:
输入:x = 3, y = 1
输出:1
解题
class Solution {
public:
int hammingDistance(int x, int y) {
int count=0;
while(x||y)
{
if(x%2!=y%2) ++count;
x/=2;
y/=2;
}
return count;
}
};
本篇文章来源于微信公众号:程序IT圈
原创文章,作者:栈长,如若转载,请注明出处:https://www.cxyquan.com/16579.html