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.
可运行代码:
#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;
}
};
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;
}
};
相关文章推荐
- LeetCode:461 Hamming Distance
- Leetcode 461 Hamming Distance 自制答案
- C++ Solution of LeetCode 461 Hamming Distance
- LeetCode 461 191 477
- LeetCode 461 Hamming Distance
- 位操作-leetcode 461 Hamming Distance
- [leetcode]461-HanmmingDistance
- leetcode 461
- LeetCode 461 Hamming Distance 汉明距离
- python--leetcode461 hamming distance
- leetcode 461:Hamming Distance
- leetcode python 461
- Leetcode 461 Hamming Distance
- [LeetCode-461]Hamming Distance
- LeetCode461 Hamming Distance java The Hamming distance between two integers is the number osoluotion
- LeetCode@Bit_461_Hamming_Distance
- LeetCode 461 617 500 476 575 637
- [leetcode][461]461. Hamming Distance
- Leetcode #461 Hamming Distance
- 刷题的日常[Leetcode]——461)Hamming Distance and 476)Number complement