文章目录
问题导入
题目链接

B r i a n Brian Brian K e r n i g h a n Kernighan Kernighan 算法
记 f ( x ) f(x) f(x) 表示 x x x 和 x − 1 x-1 x−1 进行与运算所得的结果(即 f ( x ) f(x) f(x)= x x x & ( x − 1 ) (x−1) (x−1)),那么 f ( x ) f(x) f(x) 恰为 x x x 删去其二进制表示中最右侧的 1 1 1 的结果。
时间复杂度:
O
(
log
C
)
O(\log C)
O(logC),其中
C
C
C 是元素的数据范围
空间复杂度:
O
(
1
)
O(1)
O(1)
class Solution {
public:
int hammingDistance(int x, int y) {
int s = x^y, res = 0;
while(s)
{
s &= s - 1;
res++;
}
return res;
}
};
两个数之间不同位置 1 的数量升级为多个数两个数之间不同位置 1 的数量怎么求呢?
题目链接
暴力代码
class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
int res = 0;
for(int i = 0; i < nums.size(); i++)
{
for(int j = i + 1; j < nums.size(); j++)
{
int x = nums[i]^nums[j];
while(x)
{
x &= x - 1;
res++;
}
}
}
return res;
}
};
这里利用位运算技巧,我们求 n n n 个数,每个二进制1位上 0 与 1 的个数,对于每个二进制位 1 与 0 的个数有个结论, n n n 个进制位,有 x x x 个 1,那么我们就有 n − x n-x n−x 个 0,那么不同二进制位上 1 的个数有 y = x ∗ ( n − x ) y = x*(n-x) y=x∗(n−x), 1 e 9 1e9 1e9 顶多枚举到 30 位二进制位。
class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
int res = 0, n = nums.size();
for(int i = 0; i <= 30; i++)
{
int c = 0;
for(int j = 0; j < n; j++)
c += (nums[j] >> i)&1;
res += c*(n-c);
}
return res;
}
};