Add Binary Strings

PROBLEM :

Print the resultant string after adding given two binary strings

Input:

The first line of input contains an integer T denoting the number of test cases.
The first line of each test case contains two binary strings s1 and s2 separated by space.


Output:
For each test case print the resultant binary string.

Constraints:
1<=T<=70
1<=|s1|,|s2|<=200, where |s| represents the length of string s


Example:

Input:
2
1101 111
10 01

Output:
10100
11
     
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#include<malloc.h>
#include<string.h>
char * Add_Binary_Strings(char *,char *) ;
void reverse(char *,int ) ;
int main()
 {
int t ;
char *str1,*str2 ;
str1=(char*)malloc(200*sizeof(char)) ;
str2=(char*)malloc(200*sizeof(char)) ;
cin>>t ;
while(t--)
{
   cin>>str1 ;
   cin>>str2 ;
 
   str1=Add_Binary_Strings(str1,str2) ;
   cout<<str1<<endl ;
}
return 0;
}

char * Add_Binary_Strings(char *str1,char *str2)
{
    char *add ;
    add=(char*)malloc(400*sizeof(char)) ;
   
    int l1,l2 ;
    l1=strlen(str1) ;
    l2=strlen(str2) ;
   
    reverse(str1,l1) ;
    reverse(str2,l2) ;
   
    int x,y,rem,sum,k ;
    x=0 ;
    y=0 ;
    rem=0 ;
    k=0 ;
   
    while(str1[x]!='\0'&&str2[y]!='\0')
    {
    sum=str1[x]+str2[y]+rem ;
    if(sum==97)
    {
    rem=0 ;
    add[k]='1' ;
    k++ ;
}
else if(sum==99)
{
   rem=1 ;
   add[k]='1' ;
   k++ ;
}
else
{
rem=1 ;
add[k]='0' ;
k++ ;
}
x++ ;
y++ ;
}

if(str1[x]!='\0')
while(str1[x]!='\0')
{
sum=str1[x]+rem ;
if(sum==50)
    {
    rem=1 ;
    add[k]='0' ;
    k++ ;
}
else
{
rem=0 ;
add[k]='1' ;
k++ ;
}
x++ ;
}

while(str2[y]!='\0')
{
sum=str2[y]+rem ;
if(sum==50)
    {
    rem=1 ;
    add[k]='0' ;
    k++ ;
}
else
{
rem=0 ;
add[k]='1' ;
k++ ;
}
y++ ;
}

if(rem==1)
{
add[k]='1' ;
k++ ;
}
add[k]='\0' ;

reverse(add,k) ;
return add ;
}

void reverse(char *str,int len)
{
    char temp ;
    int i,j ;
   
    i=0;
    j=len-1 ;
   
    while(i<j)
    {
        temp=str[i] ;
        str[i]=str[j] ;
        str[j]=temp ;
       
        i++ ;
        j-- ;
    }
}

---------------------------------------------------------------------------------

Comments

Post a Comment

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )