code:
#include <iostream>
#include <cmath>
#include <vector>
#include<algorithm>
using namespace std;
//This is the solution of n-bit binary integer Array addition both are of same size
vector<int> binaryArrayAddition(vector<int> &A, vector<int> &B)
{
vector<int>c;
c.reserve(A.size());//This will allocate the vector of the constant size
int carry = 0; // This is for the binary Addition carray
for (int i = A.size() - 1; i >= 0; i--)
{
int s = A[i] + B[i] + carry;
c.push_back(s % 2); // It is either 1 or 0
carry = ~~(s / 2); // for the carry
}
c.push_back(carry); // becuase we are moving from the left
// c.reserve(A.size()+1); // This will reverse the vector
reverse(c.begin(),c.end());
return c;
}
int main()
{
vector<int> a{1, 1, 1, 1};
vector<int> b{1, 1, 1, 1};
vector<int> c;
c = binaryArrayAddition(a, b);
for (auto i : c)
{
cout << i << " ";
}
return 0;
}
Output: