forked from VinayBelwal/Hactober-22-Programs-and-Projects-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddBinary
31 lines (30 loc) · 709 Bytes
/
addBinary
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
string addBinary(string a,string b){
int carry=0;
string res="";
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
int i=0,sum;
while(i<a.size() || i<b.size())
{
sum= carry;
if(i<a.size()) sum+= a[i]-'0';
if(i<b.size()) sum+= b[i]-'0';
if(sum==0) carry=0, res+='0';
else if(sum==1) carry=0, res+='1';
else if(sum==2)carry=1, res+='0';
else carry=1, res+='1';
i++;
}
if(carry==1) res+='1';
reverse(res.begin(),res.end());
return res;
}
int main()
{
string a = "1010";
string b = "1011";
cout<<addBinary(a,b)<<endl;
}