LeetCode 477. 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 0 to 10^9
2. Length of the array will not exceed 10^4.

解题代码

    public int totalHammingDistance(int[] nums) {
int sum = 0;
for (int i = 0; i < 32; i++) {
int ones = 0;
for (int j = 0; j < nums.length; j++)
ones += (nums[j] >> i) & 0x1;
sum += ones * (nums.length - ones);
}
return sum;
}
• 本文已收录于以下专栏：

Leetcode 477. Total Hamming Distance-java

1 解题思想 题目的意思就是给了一个数组，现在求总的海明距离，其中：  1、海明距离：任意两个数在二级制的表示下（int = 32bit），每个bit对应的值是1或0，那么这两个数在这32个位置下，...
• xiaopihaierletian
• 2016年12月27日 21:07
• 495

477. Total Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bi...
• liuchenjane
• 2016年12月18日 12:44
• 1280

leetcode 477 Total Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits...
• feifeiiong
• 2017年03月26日 21:13
• 125

Leetcode Total Hamming Distance 477

The Hamming distance between two integers is the number of positions at which the corresponding bits...
• huaxixidongbeishida
• 2016年12月18日 16:54
• 588

leetcode 477 Total Hamming Distance C++

• a2331046
• 2017年01月04日 14:59
• 296

【LeetCode-477】Total Hamming Distance

• cold2wind
• 2016年12月20日 16:46
• 368

leetcode 477. Total Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits...
• a1025461748
• 2017年06月11日 22:49
• 51

Leetcode: 477. Total Hamming Distance

Leetcode: 477. Total Hamming Distance
• qq_16318319
• 2017年06月26日 12:53
• 118

[leetcode] 477. Total Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bi...
• TstsUgeg
• 2016年12月20日 17:43
• 132

[leetcode]477. Total Hamming Distance

• xiaocong1990
• 2017年01月09日 16:37
• 70

举报原因： 您举报文章：LeetCode 477. Total Hamming Distance 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)