How does bitwise or in c++work?

I'm trying to solve the problem "Delete or maximize" (site-Timus Online Judges, number-2110) I don't understand how bitwise or works in the pros at all.

#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std; 
int count(string el) {
    int a = 0;
    for (int i = 0; i < el.length(); i++) {
        if (el[i] == '0') { a++; }
    }
    return a;
}
int main()
{
    int a = 0, n, k, max = -999999999, it, sum = 0;
    bool flag = 1;
    cin >> n >> k;
    if (n == k) { cout << 0; return 0; }
    vector <string> dvoichnoe(n);
    vector <int> ch(n), copy(n);
    for (int i = 0; i < n; i++){
        cin >> ch[i];
        copy[i] = ch[i];
        if (ch[i] == 0) { dvoichnoe[i] = "0"; flag = 0; }
        if (flag) {
        while (ch[i] / 2 != 0) {
            dvoichnoe[i].append(to_string(ch[i] % 2));
            ch[i] = ch[i] / 2;
        }
        dvoichnoe[i].append("1");
        reverse(dvoichnoe[i].begin(), dvoichnoe[i].end());
        }
        flag = 1;
    }
    copy = ch;
    while (k != 0){
        for (int i = 0; i < dvoichnoe.size(); i++) {
            a = count(dvoichnoe[i]);
            if (a > max) { max = a; it = i; }
        }
        dvoichnoe.erase(dvoichnoe.begin() + it, dvoichnoe.begin() + it + 1);
        copy.erase(copy.begin() + it, copy.begin() + it + 1);
        k--;
    }
    for (int i = 0; i < dvoichnoe.size() - 1; i++) {
        sum += stoi(dvoichnoe[i]) | stoi(dvoichnoe[i + 1]);
    }
    cout << sum;
}

With input data 4 1 98765432 98765432 98765432 1 outputs std:: out_of_range in the string where I'm looking for the sum, even though i doesn't go beyond the array bounds, and in general, I don't understand how the bitwise or

Author: verybadcoder, 2020-10-09

2 answers

As far as I understand, you are trying to write string representations of the binary representation of numbers to the dvoichnoe vector (although you turned this attempt into a mess). The number 98765432 will have the value 0101111000110000101001111000 in binary form, and you will have this string in the vector. And stoi("0101111000110000101001111000")? tries to return int(101111000110000101001111000) to you, and this int value does not fit. Therefore, you get an error related to the output of the range of the memory cell.

And as a tip, you'd better rethink the whole approach to solving the problem.

 4
Author: AR Hovsepyan, 2020-10-09 15:42:56

Numbers in the computer are represented as a sequence of zeros and ones, bitwise operations are performed on each bit of the original number, the numbers

For example, 2 | 5 = 7, because 2 - 010 in binary notation, 5 - 101, 010 | 101 = 111, what is in the decimal system 7

#include <iostream>

int main()
{
  std::cout << (2 | 5) << '\n'; // 7

  return 0;
}
 4
Author: Ildar, 2020-10-09 14:34:33