您的位置:首页 > 编程语言 > C语言/C++

LeetCode[461]Hamming Distance

2017-09-20 19:15 232 查看
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
↑   ↑

The above arrows point to positions where the corresponding bits are different.


可运行代码:

#include<iostream>
using namespace std;

/*
解题思路:首先计算x^y,这样不同为1,相同为0,然后再查结果中1的个数
查的方法是结果与1进行&运算,累加求和,然后再向右移位。
*/
int hammingDistance(int x, int y);

int main()
{
int x = 1;
int y = 4;
int counts;
counts = hammingDistance(x, y);
cout << counts << endl;

system("pause");
return 0;
}

int hammingDistance(int x, int y)
{
int z = 0;
z = x^y;//相同为0,不同为1
int counts = 0;
int tmp;
while (z != 0)
{
tmp = z & 1;
counts = counts + tmp;
z = z >> 1;
}
return counts;

}

提交代码:
class Solution {
public:
int hammingDistance(int x, int y)
{
int z=0;
z = x^y;//相同为0,不同为1
int counts = 0;
int tmp = 0;
while(z!=0)
{
tmp = z&1;
counts = counts+tmp;
z = z>>1;
}
return counts;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ leetcode