LintCode 1217. Total Hamming Distance JavaScript Algorithm

description

The Hamming distance between two integers is the number of positions where the corresponding bits are different.

Now your job is to find the total Hamming distance between all given pairs of numbers.

Description

1. The elements of a given array are in the range of 0 to 10^9.
2. The length of the array does not exceed 10^4.

Sample

-1:

输入: [4, 14, 2]
输出: 6
解释:在二进制表示中,40100,141110,20010(只是显示在这种情况下相关的四个位)。 所以答案是:
汉明距离(4,14) + 汉明距离(4,2) + 汉明距离(14,2) = 2 + 2 + 2 = 6-2:

输入: [2, 1, 0]
输出: 4
解释:在二进制表示中,210,101,000(只是显示在这种情况下相关的四个位)。 所以答案是:
汉明距离(2,1) + 汉明距离(1,0) + 汉明距离(2,0) = 2 + 1 + 1 = 4

Parsing

Refer to 835. Hamming distance

totalHammingDistance = function (nums) {
    
    
    var total = 0,n = nums.length;
    for (var j = 0; j < 32; j++) {
    
    
        var bitCount = 0;
        for (var i = 0; i < n; i++) {
    
     
            bitCount += (nums[i] >> j) & 1;
        }
        total += bitCount*(n - bitCount);
    }
    return total;
}


operation result

Insert picture description here

Guess you like

Origin blog.csdn.net/SmallTeddy/article/details/108635588