-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHamming Distance.cpp
More file actions
77 lines (42 loc) · 1.12 KB
/
Copy pathHamming Distance.cpp
File metadata and controls
77 lines (42 loc) · 1.12 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
66
67
68
69
70
71
72
73
74
75
76
77
Problem Description
Hamming distance between two non-negative integers is defined as the number of positions at which the corresponding bits are different.
Given an array A of N non-negative integers, find the sum of hamming distances of all pairs of integers in the array. Return the answer modulo 1000000007.
Problem Constraints
1 <= |A| <= 200000
1 <= A[i] <= 109
Input Format
First and only argument is array A.
Output Format
Return one integer, the answer to the problem.
Example Input
Input 1:
A = [1]
Input 2:
A = [2, 4, 6]
Example Output
Output 1:
0
Output 2:
8
Example Explanation
Explanation 1:
No pairs are formed.
Explanation 2:
We return, f(2, 2) + f(2, 4) + f(2, 6) + f(4, 2) + f(4, 4) + f(4, 6) + f(6, 2) + f(6, 4) + f(6, 6) = 8
// O(n^2)
int Solution::hammingDistance(const vector<int> &a) {
int n=a.size();
int cnt=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
int x=a[i];
int y=a[j];
int tmp=x^y;
while(tmp>0){
cnt+=tmp & 1;
tmp=tmp>>1;
}
}
}
return cnt;
}