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, 2Output: 6Explanation: In binary rePResentation, the 4 is 0100, 14 is 1110, and 2 is 0010 (justshowing 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 of0to10^9Length of the array will not exceed10^4.思路:一個(gè)有多個(gè)0,1組成的序列,所有的漢明距離和為0的個(gè)數(shù)乘以1的個(gè)數(shù)
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;}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注