File tree Expand file tree Collapse file tree 1 file changed +18
-16
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +18
-16
lines changed Original file line number Diff line number Diff line change 1
1
package com .fishercoder .solutions ;
2
2
3
3
/**
4
+ * 477. Total Hamming Distance
5
+ *
4
6
* The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
5
7
6
8
Now your job is to find the total Hamming distance between all pairs of the given numbers.
7
9
8
10
Example:
9
11
Input: 4, 14, 2
10
-
11
12
Output: 6
12
-
13
13
Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
14
14
showing the four bits relevant in this case). So the answer will be:
15
15
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
16
+
16
17
Note:
17
18
Elements of the given array are in the range of 0 to 10^9
18
19
Length of the array will not exceed 10^4.
19
20
*/
20
21
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
+ }
33
35
}
36
+ r += one * zero ;
34
37
}
35
- r += one * zero ;
38
+ return r ;
36
39
}
37
- return r ;
38
40
}
39
41
40
42
}
You can’t perform that action at this time.
0 commit comments