Skip to content

Commit df459ab

Browse files
refactor 477
1 parent ee34534 commit df459ab

File tree

1 file changed

+18
-16
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+18
-16
lines changed
Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,42 @@
11
package com.fishercoder.solutions;
22

33
/**
4+
* 477. Total Hamming Distance
5+
*
46
* The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
57
68
Now your job is to find the total Hamming distance between all pairs of the given numbers.
79
810
Example:
911
Input: 4, 14, 2
10-
1112
Output: 6
12-
1313
Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
1414
showing the four bits relevant in this case). So the answer will be:
1515
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
16+
1617
Note:
1718
Elements of the given array are in the range of 0 to 10^9
1819
Length of the array will not exceed 10^4.
1920
*/
2021
public class _477 {
21-
22-
public int totalHammingDistance(int[] nums) {
23-
int r = 0;
24-
for (int i = 0; i < 32; i++) {
25-
int one = 0;
26-
int zero = 0;
27-
int bit = 1 << i;
28-
for (int n : nums) {
29-
if ((n & bit) != 0) {
30-
one++;
31-
} else {
32-
zero++;
22+
public static class Solution1 {
23+
public int totalHammingDistance(int[] nums) {
24+
int r = 0;
25+
for (int i = 0; i < 32; i++) {
26+
int one = 0;
27+
int zero = 0;
28+
int bit = 1 << i;
29+
for (int n : nums) {
30+
if ((n & bit) != 0) {
31+
one++;
32+
} else {
33+
zero++;
34+
}
3335
}
36+
r += one * zero;
3437
}
35-
r += one * zero;
38+
return r;
3639
}
37-
return r;
3840
}
3941

4042
}

0 commit comments

Comments
 (0)