-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_binary_strings.cpp
More file actions
140 lines (80 loc) · 1.61 KB
/
add_binary_strings.cpp
File metadata and controls
140 lines (80 loc) · 1.61 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#include"essentials.cpp"
void make_equal_length(string &s1,string &s2){
int length1=s1.length();
int length2=s2.length();
reverse(s2.begin(),s2.end());
int diff=length1-length2;
for(int i=0;i<diff;i++ ){
s2+='0';
}
reverse(s2.begin(),s2.end());
}
string add_binary(string a, string b){
int length1=a.length();
int length2=b.length();
int carry=0;
string result="";
if(length1>length2){
make_equal_length(a,b);
}
else{
make_equal_length(b,a);
}
cout<<a<<" "<<b<<endl;
for(int i=a.length()-1,j=b.length()-1;i>=0,j>=0;i--,j--){
if(a[i]=='0' && b[i]=='0')
{
if(carry==1)
{result+='1';
carry=0;}
else{
result+='0';
}
cout<<"1 :"<<result<<endl;
}
else if(a[i]=='1' && b[i]=='1'){
if(carry==0){
result+='0';
carry=1;
}
else{
result+='1';
carry=1;
}
cout<<"2 :"<<result<<endl;
}
else if(a[i]=='1' && b[i]=='0'){
if(carry==0){
result+='1';
}
else{
result+='0';
carry=1;
}
cout<<"3 :"<<result<<endl;
}
else if(a[i]=='0' && b[i]=='1'){
if(carry==0){
result+='1';
}
else{
result+='0';
carry=1;
}
cout<<"4 :"<<result<<endl;
}
}
if(carry==1)
result+=to_string(carry);
reverse(result.begin(),result.end());
return result;
}
int main(){
string a="1010";
string b="1011";
string result;
result=add_binary(a,b);
cout<<result<<endl;
cout<<a<<" "<<b<<endl;
return 1;
}