Home » Interview Questions » String Interview Questions » Program to add two binary digits

Program to add two binary digits


()

Given two binary strings, write a function that print the sum of the giiven two binary strings. where sum is also a binary string

Example

INPUT
s1 = “101”
s2 =”11″

OUTPUT
res = “1000”

Algorithm

1. Start from the last character in both strings

2. Add the characters in both strings one by one, if the sum is more than 1, then store 1 as a carry which will be added for next digits

C++ Program

#include <bits/stdc++.h>
using namespace std;


string addBinaryStrings(string s1, string s2)
{
	string res = "";
	int sum = 0, carry = 0;
	int i = s1.length()-1;
	int j = s2.length()-1;
	while(i>=0 || j>=0 || sum == 1)
	{
		//calculating the sum of both elements in s1 and s2
        //If there there is no elment in any string, just add elements from other string
	    sum = carry + (i>=0? s1[i]-'0':0) + (j>=0? s2[j]-'0':0);
	    // update carry for next calulation
        // update sum if it is greater than 1
	    if (sum>1)
	    {
	    	sum = 0;
	    	carry = 1;
	    }
	    else
	    {
	    	carry = 0;
	    }
	    //adding sum to result
	    res = char(sum + '0') + res;
	    i--;
	    j--;
	}
	if (carry == 1)
	{
		res = char(carry + '0') + res;
	}
	return res;
}

int main()
{
	string s1 = "101";
	string s2 = "11";
	cout<<addBinaryStrings(s1,s2)<<endl;
}

Try It

 

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote Count

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions