[LeetCode]461. Hamming Distance
2017-05-09 20:19
302 查看
The Hamming distance between two integers is the number of positions at which the corresponding bits are
different.
Given two integers
calculate the Hamming distance.
汉明距离:两个数用二进制表示时,两数对应位不同的个数。可将两数异或,再算得出结果的各个位上的1的个数。
如十进制除以10,求二进制数各个位上1的个数,可以将其一直除以2,将其余数个数相加。
1版:
2.看到 x&(x-1) 可以消去x最右位的1
2版
class Solution {
public:
int hammingDistance(int x, int y) {
int i = 0;
int temp = x^y;
while (temp)
{
temp &= (temp - 1);
i++;
}
return i;
}
};
3版 简化1
class Solution {
public:
int hammingDistance(int x, int y) {
if ((x^y) == 0)
return 0;
return (x^y) % 2 + hammingDistance(x / 2, y / 2);
}
};
different.
Given two integers
xand
y,
calculate the Hamming distance.
汉明距离:两个数用二进制表示时,两数对应位不同的个数。可将两数异或,再算得出结果的各个位上的1的个数。
如十进制除以10,求二进制数各个位上1的个数,可以将其一直除以2,将其余数个数相加。
1版:
class Solution { public: int hammingDistance(int x, int y) { int temp; int i = 0;//计数 temp = x^y; while (temp / 2 != 0) { if (temp % 2 == 1) i++; temp = temp / 2; } if (temp == 1) i++; return i; } };
2.看到 x&(x-1) 可以消去x最右位的1
2版
class Solution {
public:
int hammingDistance(int x, int y) {
int i = 0;
int temp = x^y;
while (temp)
{
temp &= (temp - 1);
i++;
}
return i;
}
};
3版 简化1
class Solution {
public:
int hammingDistance(int x, int y) {
if ((x^y) == 0)
return 0;
return (x^y) % 2 + hammingDistance(x / 2, y / 2);
}
};
相关文章推荐
- LeetCode: 461. Hamming Distance
- [Leetcode] 461. Hamming Distance 解题报告
- 【LeetCode】461. Hamming Distance
- leetcode 461. Hamming Distance
- leetcode_461. Hamming Distance 计算汉明距离,按位异或运算,计算整数的二进制表示中1的个数 java
- LeetCode 461. Hamming Distance
- LeetCode 461. Hamming Distance
- 【LeetCode】 461. Hamming Distance
- leetcode 461. Hamming Distance
- leetcode 461. Hamming Distance
- LeetCode 461. Hamming Distance(java)
- LeetCode#461. Hamming Distance
- LeetCode 461. Hamming Distance 知识点复习之位运算
- [LeetCode]461. Hamming Distance(汉明距离)
- leetcode 461. Hamming Distance
- LeetCode | 461. Hamming Distance 12_16
- LeetCode :【Easy】461. Hamming Distance
- LeetCode 461. Hamming Distance(Java)
- Leetcode - 461. Hamming Distance n&=(n-1) (C++)
- leetcode 461. Hamming Distance