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

# Program to add two binary digits

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 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;
}
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";