LeetCode: Total Hamming Distance
2017-02-09 11:03
387 查看
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:
Note:
Elements of the given array are in the range of
Length of the array will not exceed
思路:一个有多个0,1组成的序列,所有的汉明距离和为0的个数乘以1的个数
int totalHammingDistance(int* nums, int numsSize) {
int totalD = 0;
int bits[32];
for (int i = 0; i < 32; ++i) {
bits[i] = 0;
}
for (int i = 0; i < numsSize; ++i) {
for (int j = 0; j < 32; ++j) {
bits[j] += nums[i] & 1;
nums[i] >>= 1;
}
}
for (int i = 0; i < 32; ++i) {
totalD += bits[i] * (numsSize - bits[i]);
}
return totalD;
}
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
0to
10^9
Length of the array will not exceed
10^4.
思路:一个有多个0,1组成的序列,所有的汉明距离和为0的个数乘以1的个数
int totalHammingDistance(int* nums, int numsSize) {
int totalD = 0;
int bits[32];
for (int i = 0; i < 32; ++i) {
bits[i] = 0;
}
for (int i = 0; i < numsSize; ++i) {
for (int j = 0; j < 32; ++j) {
bits[j] += nums[i] & 1;
nums[i] >>= 1;
}
}
for (int i = 0; i < 32; ++i) {
totalD += bits[i] * (numsSize - bits[i]);
}
return totalD;
}
相关文章推荐
- [leetcode, python] Total Hamming Distance 多个数字之间的汉明距离
- leetcode-477-Total Hamming Distance
- [leetcode, python] Total Hamming Distance 多个数字之间的汉明距离
- LeetCode Total Hamming Distance
- [leetcode, python] Total Hamming Distance 多个数字之间的汉明距离
- leetcode 477 Total Hamming Distance
- Leetcode Total Hamming Distance 477
- LeetCode Weekly Contest 13-TotalHamming Distance【中】
- [leetcode, python] Total Hamming Distance 多个数字之间的汉明距离
- leetcode 477 Total Hamming Distance C++
- Leetcode 477 Total Hamming Distance
- [leetcode, python] Total Hamming Distance 多个数字之间的汉明距离
- [leetcode, python] Total Hamming Distance 多个数字之间的汉明距离
- [LeetCode] Total Hamming Distance 全部汉明距离
- [leetcode, python] Total Hamming Distance 多个数字之间的汉明距离
- [leetcode, python] Total Hamming Distance 多个数字之间的汉明距离
- [leetcode, python] Total Hamming Distance 多个数字之间的汉明距离
- LeetCode No.477 TotalHammingDistance
- leetcode-Total Hamming Distance
- [leetcode, python] Total Hamming Distance 多个数字之间的汉明距离