Program to add two binary strings, and return also as binary string in C++

PythonServer Side ProgrammingProgramming

Suppose we have two binary strings a and b, we have to add these binary numbers and find their sum, also as a string.

So, if the input is like a = "10110", b = "10010", then the output will be "101000".

To solve this, we will follow these steps −

  • ret := empty string
  • na := size of a, nb := size of b
  • i := na - 1, j := nb - 1
  • carry := 0
  • while (i >= 0 or j >= 0), do:
    • addA := (if i >= 0, then a[i] - ASCII of '0', otherwise 0)
    • addB := (if j >= 0, then b[j] - ASCII of '0', otherwise 0)
    • sum := addA + addB + carry
    • carry := sum / 2
    • sum := sum mod 2
    • ret := ret concatenate sum
    • (decrease i by 1)
    • (decrease j by 1)
  • if carry is non-zero, then:
    • ret := ret concatenate carry
  • reverse the array ret
  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string solve(string a, string b){
      string ret = "";
      int na = a.size();
      int nb = b.size();
      int i = na - 1;
      int j = nb - 1;
      int carry = 0;
      while(i >= 0 || j >= 0){
         int addA = i >= 0 ? a[i] - '0' : 0;
         int addB = j >= 0 ? b[j] - '0' : 0;
         int sum = addA + addB + carry;
         carry = sum / 2;
         sum %= 2;
         ret += to_string(sum);
         i--;
         j--;
      }
      if(carry)
         ret += to_string(carry); reverse(ret.begin(), ret.end());
         return ret;
   }
};
main(){
   string a = "10110", b = "10010"; Solution ob;
   cout << ob.solve(a, b);
}

Input

"10110","10010"

Output

101000
raja
Published on 05-Oct-2020 12:16:48
Advertisements