-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd_binary_strings.cpp
More file actions
50 lines (50 loc) · 1.01 KB
/
Add_binary_strings.cpp
File metadata and controls
50 lines (50 loc) · 1.01 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
string Solution::addBinary(string A, string B) {
int a = A.size();
int b = B.size();
if(b>a){
swap(a,b);
swap(A,B);
}
int count = a-b;
string tmp = "";
while(count--){
tmp += '0';
}
B = tmp+B;
b = a;
tmp = "";
int carry = 0;
for(int i=a-1;i>=0;i--){
if(A[i]=='1' && B[i]=='1'){
if(carry==1){
tmp += '1';
}
else{
tmp += '0';
carry = 1;
}
}
else if(A[i]=='1' && B[i]=='0' || A[i]=='0' && B[i]=='1'){
if(carry==1){
tmp += '0';
}
else{
tmp += '1';
}
}
else{
if(carry==1){
tmp += '1';
carry = 0;
}
else{
tmp += '0';
carry = 0;
}
}
}
if(carry==1)
tmp += '1';
reverse(tmp.begin(),tmp.end());
return tmp;
}