File tree 1 file changed +19
-37
lines changed
src/main/java/com/fishercoder/solutions 1 file changed +19
-37
lines changed Original file line number Diff line number Diff line change 1
1
package com .fishercoder .solutions ;
2
2
3
- /**
4
- * 477. Total Hamming Distance
5
- *
6
- * The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
7
-
8
- Now your job is to find the total Hamming distance between all pairs of the given numbers.
9
-
10
- Example:
11
- Input: 4, 14, 2
12
- Output: 6
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
-
17
- Note:
18
- Elements of the given array are in the range of 0 to 10^9
19
- Length of the array will not exceed 10^4.
20
- */
21
3
public class _477 {
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
- }
35
- }
36
- r += one * zero ;
37
- }
38
- return r ;
39
- }
40
- }
4
+ public static class Solution1 {
5
+ public int totalHammingDistance (int [] nums ) {
6
+ int r = 0 ;
7
+ for (int i = 0 ; i < 32 ; i ++) {
8
+ int one = 0 ;
9
+ int zero = 0 ;
10
+ int bit = 1 << i ;
11
+ for (int n : nums ) {
12
+ if ((n & bit ) != 0 ) {
13
+ one ++;
14
+ } else {
15
+ zero ++;
16
+ }
17
+ }
18
+ r += one * zero ;
19
+ }
20
+ return r ;
21
+ }
22
+ }
41
23
42
24
}
You can’t perform that action at this time.
0 commit comments