Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathTotal Hamming Distance.java
More file actions
Latest commit
executable file
·65 lines (51 loc) · 2.18 KB
/
Copy pathTotal Hamming Distance.java
File metadata and controls
executable file
·65 lines (51 loc) · 2.18 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
60
61
62
63
64
65
M
1531598157
tags: BitManipulation
time: O(n)
space: O(1), 32-bitarray
给出HammingDistance定义(bitformat时候有多少binarydiff), 求一串数字的hammingdistance总和.
#### BitManipulation
- Bit题: 考验bit >>, mask & 1, 还有对题目的理解能力
- Putintegersinbinary, andcompareeachcolumn:
- foreach `1`, ask: howmanyaredifferentfromme? allthe `0`
- `# ofdiffsateachbit-column = #ofZero * #ofOne `
- 1.countZero[], countOne[]; 2.loopovernumsandpopulatethetwoarray
##### 注意雷点
- 问清楚: 10^9 < 2^31, weareokaywith32bits
- `最终的hammingdistance 要从 [1 ~ 32] 哪个bit开始算起`? 取决于 `最长`的那个binaryformat: 但不用先去找bitlength
- 在做countZero, countOne时候, 都做32-bit; 最终做乘积的时候, 如果 `1` 或者 `0` 个数为零, 乘积自然为0.
```
/*
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the given numbers.
Example:
Input: 4, 14, 2
Output: 6
Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case). So the answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
Note:
Elements of the given array are in the range of 0 to 10^9
Length of the array will not exceed 10^4.
*/
// bit manipulation
classSolution {
publicinttotalHammingDistance(int[] nums) {
intrst = 0;
if (nums == null || nums.length == 0) returnrst; // check input
// populate over all nums
int[] countZero = newint[32], countOne = newint[32];
for (intnum : nums) populateBinaryCount(countZero, countOne, num);
// calc final result
for (inti = 0; i < 32; i++) rst += countZero[i] * countOne[i];
returnrst;
}
privatevoidpopulateBinaryCount(int[] countZero, int[] countOne, intnum) {
for (inti = 0; i < 32; i++){
if ((num & 1) == 1) countOne[i]++;
elsecountZero[i]++;
num = (num >> 1);
}
}
}
```