Skip to content

Commit b1f357e

Browse files
author
freemanzhang
committed
init impl
1 parent 73f3034 commit b1f357e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package string;
2+
3+
/*
4+
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
5+
6+
Now your job is to find the total Hamming distance between all pairs of the given numbers.
7+
8+
Example:
9+
Input: 4, 14, 2
10+
11+
Output: 6
12+
13+
Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
14+
showing the four bits relevant in this case). So the answer will be:
15+
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
16+
Note:
17+
Elements of the given array are in the range of 0 to 10^9
18+
Length of the array will not exceed 10^4.
19+
* */
20+
21+
public class TotalHammingDistance
22+
{
23+
public int totalHammingDistance( int[] nums )
24+
{
25+
int n = 31;
26+
int len = nums.length;
27+
int[] numOfOnes = new int[n];
28+
29+
for ( int i = 0; i < len; i++ )
30+
{
31+
for ( int j = 0; j < n; j++ )
32+
{
33+
numOfOnes[j] += ( nums[i] >> j ) & 1;
34+
}
35+
}
36+
37+
int sum = 0;
38+
for ( int count : numOfOnes )
39+
{
40+
sum += count * ( len - count );
41+
}
42+
return sum;
43+
}
44+
}

0 commit comments

Comments
 (0)