-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTotalHammingDistance.java
More file actions
59 lines (50 loc) · 1.48 KB
/
TotalHammingDistance.java
File metadata and controls
59 lines (50 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package leetcode;
/**
* TotalHammingDistance
* https://leetcode-cn.com/problems/total-hamming-distance/
* 477. 汉明距离总和
* https://leetcode-cn.com/problems/total-hamming-distance/solution/jie-zhu-pai-lie-jie-ti-by-oshdyr-2t34/
*
* @since 2021-05-28
*/
public class TotalHammingDistance {
public static void main(String[] args) {
TotalHammingDistance sol = new TotalHammingDistance();
System.out.println(sol.totalHammingDistance(new int[]{4, 14, 2}));
}
public int totalHammingDistance(int[] nums) {
int[] counts = new int[32];
int length = nums.length;
for (int i = 0; i < length; i++) {
int tmp = nums[i];
for (int j = 0; j < 32; j++) {
counts[j] += (tmp & 1);
tmp >>= 1;
}
}
int total = 0;
for (int i = 0; i < 32; i++) {
total += (counts[i] * (length - counts[i]));
}
return total;
}
public int totalHammingDistance2(int[] nums) {
int length = nums.length;
int total = 0;
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
total += hammingDistance(nums[i], nums[j]);
}
}
return total;
}
public int hammingDistance(int a, int b) {
int tmp = a ^ b;
int size = 0;
while (tmp != 0) {
tmp = tmp & (tmp - 1);
size += 1;
}
return size;
}
}