Advertisement
jasonpogi1669

Maintaining Bit Frequency to Find OR Operation Result in a Sequence using C++

Dec 24th, 2021
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. // this function adds/subtracts every set bit of a number (OR operation)
  6. void BitFrequency(int x, int* frequency, int add_sub) {
  7.     for (int i = 0; i < 32; i++) {
  8.         if (x & (1 << i)) {
  9.             frequency[i] += add_sub;
  10.         }
  11.     }
  12. }
  13.  
  14. // this function converts to decimal representation from a binary representation
  15. int Calculate(int frequency[]) {
  16.     int ans = 0;
  17.     for (int i = 0; i < 32; i++) {
  18.         if (frequency[i] >= 1) {
  19.             ans += (1 << i);
  20.         }
  21.     }
  22.     return ans;
  23. }
  24.  
  25. int main() {
  26.     int n;
  27.     cin >> n;
  28.     int a[n];
  29.     for (int i = 0; i < n; i++) {
  30.         cin >> a[i];
  31.     }
  32.     int frequency[32] = {0};
  33.     for (int i = 0; i < n; i++) {
  34.         BitFrequency(a[i], frequency, 1);
  35.     }
  36.     int ans = Calculate(frequency);
  37.     cout << ans << '\n';
  38.     return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement