In this program, we need to give binary numbers and add them. There are n binary numbers and we need to add them all to get a binary number as output.
To do this, we will use binary addition logic to add all the items from 1 to N one by one to get the result.
Input: "1011", "10", "1001" Output: 10110
A simpler way is to convert the binary string to its decimal equivalent, then add them together and convert to binary again. Here we will add it manually. We will use a helper function to add two binary strings. This function will be used n-1 times against n different binary strings.
#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; }
The above is the detailed content of Add n binary strings?. For more information, please follow other related articles on the PHP Chinese website!