461. Hamming Distance*(汉明距离)
https://leetcode.com/problems/hamming-distance/
题目描述
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.
Example 1:
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.
Example 2:
Input: x = 3, y = 1
Output: 1
Constraints:
0 <= x, y <= 2^31 - 1
C++ 实现 1
这类和二进制位的问题, 需要记住一些结论, 这些结论在 191. Number of 1 Bits* 和 231. Power of Two 这些题中也出现了, 即对于一个整数 n, 它和 n - 1 进行 “与” 操作(即 &), 可以将 n 的二进制表示中最右边的 1 给删除.
比如 n = 0x00001100, 那么 n & (n - 1) 的结果为 0x00001000. 这样的话, 使用
int count = 0;
while (n) {
n &= (n - 1);
count += 1;
}
这段代码, 可以用于整数 n 的二进制表示中 1 的个数.
知晓上面的结论, 再来求解本题, 相当容易了, 先计算 res = x ^ y, 即两个整数的异或, 再统计 res 的二进制表示中 1 的个数即可.
class Solution {
private:
int countBits(int n) {
int count = 0;
while (n) {
count += 1;
n &= (n - 1);
}
return count;
}
public:
int hammingDistance(int x, int y) {
int res = x ^ y;
return countBits(res);
}
};
> 这里是引用
本文解析了如何使用C++中的异或操作和位计数技巧解决LeetCode上的汉明距离问题。通过理解整数与操作删除最右边的1,演示了如何在Solution类中利用countBits方法计算两个整数的异或结果中1的个数,从而得到汉明距离。

3万+

被折叠的 条评论
为什么被折叠?



