[InterviewBit] Different Bits Sum Pairwise

Different Bits Sum Pairwise

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int Solution::cntBits(vector<int> &A) {
vector<int> freq(32);
for(int i = 0; i < A.size(); i++) {
for(int j = 0; j < 32; j++) {
if(A[i] & (1<<j)) freq[j]++;
}
}
int res = 0, mod = 1e9 + 7, n = A.size();
for(int i = 0; i < n; i++) {
for(int j = 0; j < 32; j++) {
int pos = freq[j], neg = n - freq[j];
if(A[i] & (1<<j)) res = (res + neg) % mod;
else res = (res + pos) % mod;
}
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/12/PS/interviewbit/different-bits-sum-pairwise/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.