461 - 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
, calculate the Hamming distance.
Note:
0 ≤ x
, y
< 231.
Example:
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.
直接上代码吧,也没啥好写的
时间复杂度O(32),空间复杂度O(1)
class Solution {
public:
int hammingDistance(int x, int y) {
int ans = 0;
for (int i = 0; i < 32; ++i) {
if (((x >> i) & 1) ^ ((y >> i) & 1)) ans++;
}
return ans;
}
};
再贴个评论区的代码,见过这个写法。时间复杂度O(1),空间复杂度O(1)
class Solution {
public:
int hammingDistance(int x, int y) {
int dist = 0, n = x ^ y;
while (n) {
++dist;
n &= n - 1;
}
return dist;
}
};
477. Total Hamming Distance
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the given numbers.
Example:
Input: 4, 14, 2 Output: 6 Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). So the answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
Note:
- Elements of the given array are in the range of
0
to10^9
- Length of the array will not exceed
10^4
.
整体扫一遍就好了,时间复杂度O(n*32),空间复杂度O(1),计算每一位为0为1的数有多少个,然后乘一下加起来,OK
class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
int ans = 0;
int sum1 = 0, sum2 = 0;
for (int i = 0; i < 32; ++i) {
sum1 = 0, sum2 = 0;
for (int j = 0; j < nums.size(); ++j) {
if ((nums[j] >> i) & 1) sum1++;
else sum2++;
}
ans += sum1 * sum2;
}
return ans;
}
};