Home > Backend Development > C++ > body text

Add n binary strings?

PHPz
Release: 2023-08-25 14:53:25
forward
500 people have browsed it

添加 n 个二进制字符串?

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
Copy after login

Description

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.

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] - &#39;0&#39;;
      } else {
         s += 0;
      }
      if(j >= 0) {
         s += b2[j] - &#39;0&#39;;
      } else {
         s += 0;
      }
      res = char(s % 2 + &#39;0&#39;) + 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;
}
Copy after login

The above is the detailed content of Add n binary strings?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!