Hamming Distance
程序员文章站
2024-03-19 08:28:52
...
求两个整数之间的汉明码距离,我想的是将其不断的右移,然后判断最低位是不是一样的。
代码如下:
题目来源
class Solution {
public:
int hammingDistance(int x, int y) {
int res = 0;
while (x > 0 || y > 0) {
if (x % 2 != y % 2)
res++;
x = x >> 1;
y = y >> 1;
}
return res;
}
};
然后想想实际上直接把两个数异或一下,然后判断有多少位是1。
代码如下:
class Solution {
public:
int hammingDistance(int x, int y) {
int dis = 0, n = x ^ y;
while (n > 0) {
if (((n >> 1) << 1) != n)//重点在这,通过左移再右移判断最后一位是不是1
dis++;
n >>= 1;
}
return dis;
}
};
或者直接一行代码解决:
class Solution {
public:
int hammingDistance(int x, int y) {
return bitset<32>(x^y).count();
}
};
推荐阅读
-
729 - The Hamming Distance Problem
-
The Hamming Distance Problem UVA - 729 (推荐使用 next_permutation())
-
Hamming Distance
-
The Hamming Distance [位运算]
-
1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance
-
1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance
-
Codeforces - Barcelonian Distance
-
poj 2689Prime Distance(区间素数)埃氏筛法
-
LeetCode --- 783. Minimum Distance Between BST Nodes 解题分析
-
Matrix Cells in Distance Order