fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int orSumOfPairs(int arr[], int n) {
  5. int ans = 0;
  6.  
  7. // Iterate over each bit position (0 to 31)
  8. for (int i = 0; i < 32; i++) {
  9. int k1 = 0; // Count of numbers with the i-th bit set
  10.  
  11. // Count how many numbers have this bit set
  12. for (int j = 0; j < n; j++) {
  13. if (arr[j] & (1 << i)) {
  14. k1++;
  15. }
  16. }
  17.  
  18. int k0 = n - k1; // Count of numbers without the i-th bit set
  19.  
  20. // Contribution of this bit to the OR sum
  21. ans += ((k1 * (k1 - 1)) / 2 + k1 * k0) * (1 << i);
  22. }
  23.  
  24. return ans;
  25. }
  26.  
  27. int main() {
  28. int n;
  29. cin >> n;
  30. int arr[n];
  31. for (int i = 0; i < n; i++) {
  32. cin >> arr[i];
  33. }
  34. cout << orSumOfPairs(arr, n);
  35. return 0;
  36. }
  37.  
Success #stdin #stdout 0.01s 5284KB
stdin
4
1 2 3 4
stdout
27