总的海明距离 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:

  1. Elements of the given array are in the range of to 10^9
  2. Length of the array will not exceed 10^4.

解决:

①  

4:     0 1 0 0

14:   1 1 1 0

2:     0 0 1 0

总的汉明距离 = (2 * 1) + (2 * 1) + (2 * 1) + (3 * 0) = 6,所以总的汉明距离为每个位上的1和0的数量,然后将它们相乘,然后将所有位的乘积相加。时间:O(N) ;空间: O(1)。

public class Solution { //19ms
    public int totalHammingDistance(int[] nums) {
        int sum = 0;
        for (int i = 0; i < 32; i ++) {
            int count = 0;
            for (int num : nums) {
                count += (num >> i) & 1;
            }
            sum += count * (nums.length - count);
        }
        return sum;
    }
}

转载于:https://my.oschina.net/liyurong/blog/1603313