- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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; }
- Related Articles
- Add n binary strings in C++?
- Haskell program to add binary strings
- Java Program to Add Two Binary Strings
- Program to add two binary strings in C++
- How to add Two Binary Strings in Golang?
- Bitwise AND of N binary strings in C++
- Bitwise OR of N binary strings in C++
- Program to add two binary strings, and return also as binary string in C++
- Adding binary strings together JavaScript
- Find the number of binary strings of length N with at least 3 consecutive 1s in C++
- Count number of binary strings of length N having only 0’s and 1’s in C++
- The n times dribbling strings in JavaScript
- How to add binary numbers using Python?
- Algorithm to add binary arrays in JavaScript
- How to add two or more strings in MySQL?

Advertisements