In this program, we are going to share a C++ program to add n binary strings. If you are a beginner and want to start learning the C++ programming, then keep your close attention in this tutorial as I am going to share a program for C++ program to add n binary strings with the output.
Copy the below C++ program and execute it with the help of GCC compiler. At the end of this program, We have shared the output of this program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | #include <bits/stdc++.h> using namespace std; string addBinaryUtil(string a, string b) { string result = ""; int s = 0; // Initialize digit sum int i = a.size() - 1, j = b.size() - 1; while (i >= 0 || j >= 0 || s == 1) { s += ((i >= 0) ? a[i] - '0' : 0); s += ((j >= 0) ? b[j] - '0' : 0); result = char(s % 2 + '0') + result; s /= 2; // Move to next digits i--; j--; } return result; } string addBinary(string arr[], int n) { string result = ""; for (int i = 0; i < n; i++) result = addBinaryUtil(result, arr[i]); return result; } int main() { string arr[] = { "1", "10", "11" }; int n = sizeof(arr) / sizeof(arr[0]); cout << addBinary(arr, n) << endl; return 0; } |
110
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.