Add n binary strings?


In this program we have to add binary numbers given. there are n binary numbers and we have to add them all to give one binary number as an output.

For this we will use binary addition logic and add all the terms from 1 to N one by one to gain the result.

Input: "1011", "10", "1001"
Output: 10110

Explanation

The easier method is by converting binary string to its decimal equivalent, then add them and convert into binary again. Here we will do the addition manually. We will use one helper function to add two binary strings. That function will be used for n-1 times for n different binary strings.

Example

#include<iostream>
using namespace std;
string add(string b1, string b2) {
   string res = "";
   int s = 0;
   int i = b1.length() - 1, j = b2.length() - 1;
   while (i >= 0 || j >= 0 || s == 1) {
      if(i >= 0) {
         s += b1[i] - '0';
      } else {
         s += 0;
      }
      if(j >= 0) {
         s += b2[j] - '0';
      } else {
         s += 0;
      }
      res = char(s % 2 + '0') + res;
      s /= 2;
      i--; j--;
   }
   return res;
}
string addbinary(string a[], int n) { string res = "";
   for (int i = 0; i < n; i++) {
      res = add(res, a[i]);
   }
   return res;
}
int main() {
   string arr[] = { "1011", "10", "1001" };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << addbinary(arr, n) << endl;
}

Updated on: 20-Aug-2019

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements