# leetcode477. 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 count = 0;
int length = nums.length;
for(int i = 0 ; i<32 ; i++) {
int countOfOne = 0;
for(int j = 0 ; j < length ; j++) {
countOfOne += (nums[j] >> i) & 1;
}
count += countOfOne * (length - countOfOne);
}
return count;
}```

0 条评论

• ### leetcode501. Find Mode in Binary Search Tree

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most...

• ### leetcode463. Island Perimeter

用一个二维数组来表示一块岛屿的土地情况，其中1代表土地，0代表海洋。要求计算出岛屿的周长。题目中特别强调了不存在内陆湖的存在，其实是变相的降低了题目的难度。即我...

• ### leetcode502. IPO

Suppose LeetCode will start its IPO soon. In order to sell a good price of its s...

• ### POJ2488-A Knight's Journey（DFS+回溯）

题目链接：http://poj.org/problem?id=2488 A Knight's Journey Time Limit: 1000MS ...

• ### HDU-1011 Starship Troopers（树形dp）

Starship Troopers Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536...

• ### 多语种机器翻译: 缩小共享和特定语言编码解码器之间的差距（CS CL)

最先进的多语种机器翻译依赖于通用的编码解码器，这需要重新训练整个系统来添加新的语言。 在本文中，我们提出了一种基于特定语言编码解码器的替代方法，从而可以更容易地...

• ### 【编程练习】poj1068

Let S = s1 s2...s2n be a well-formed string of parentheses. S can be encoded in...

• ### POJ-2181 Jumping Cows（贪心）

Jumping Cows Time Limit: 1000MS Memory Limit: 65536K Total Submissions:...

• ### POJ 3461 kmp

Oulipo Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 40168 ...

• ### Codeforces 626E Simple Skewness(暴力枚举+二分)

E. Simple Skewness time limit per test:3 seconds memory limit per test:256 megab...