LeetCode 477. Total Hamming Distance

来源:互联网 发布:淘宝优惠券网站 编辑:程序博客网 时间:2024/05/02 00:52

题目:

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:

  1. Elements of the given array are in the range of to 10^9
  2. Length of the array will not exceed 10^4.
思路:刚开始暴力求,只能过一半。 coincidental suddenness,昨天刚刚复习了一下基数排序,想了一下是一样的,每两个数之间没关系,考虑第k个bit,为0的有num0个,为1的有num1个,第k个bit总共能产生num0*num1个结果。所以遍历每一位就可以了,最大为10^9,遍历到30位就行。
class Solution {public:    int totalHammingDistance(vector<int>& nums) {        int sum = 0;        unsigned int t = 0x1;        for(int i = 0; i < 30; i++){            int num1 = 0, num0 = 0;            for(int j = 0; j < nums.size(); j++) {                int tmp = t&nums[j];                if(tmp>0) {                    num1++;                } else {                    num0++;                }            }            sum+=num1*num0;            t = t<<1;        }        return sum;    }};