-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add Binary Strings(potd).cpp
127 lines (113 loc) · 2.6 KB
/
Add Binary Strings(potd).cpp
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
//{ Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
string addBinary(string A, string B)
{
int carry=0;
string ans="";
int index1=A.length()-1;
int index2=B.length()-1;
while(index1>=0 && index2>=0){
if( A[index1]=='1' && B[index2]=='1'){
if(carry==1){
ans+="1";
carry=1;
}else{
ans+="0";
carry=1;
}
}else if(A[index1]=='1' && B[index2]=='0'){
if(carry==1){
ans+="0";
carry=1;
}else{
ans+="1";
carry=0;
}
}else if(A[index1]=='0' && B[index2]=='1'){
if(carry==1){
ans+="0";
carry=1;
}else{
ans+="1";
carry=0;
}
}else{
if(carry==1){
ans+="1";
carry=0;
}else{
ans+="0";
carry=0;
}
}
index1--;
index2--;
}
if(index1>=0){
while(index1>=0){
if(carry==1 && A[index1]=='1'){
ans+="0";
carry=1;
}else if(carry==0 && A[index1]=='1'){
ans+="1";
carry=0;
}
else if(carry==1 && A[index1]=='0'){
ans+="1";
carry=0;
}else{
ans+="0";
carry=0;
}
index1--;
}
}
if(index2>=0){
while(index2>=0){
if(carry==1 && B[index2]=='1'){
ans+="0";
carry=1;
}else if(carry==0 && B[index2]=='1'){
ans+="1";
carry=0;
}
else if(carry==1 && B[index2]=='0'){
ans+="1";
carry=0;
}else{
ans+="0";
carry=0;
}
index2--;
}
}
if(carry==1){
ans+="1";
}
reverse(ans.begin(),ans.end());
int i=0;
while(i<ans.length() && ans[i]=='0'){
i++;
}
return ans.substr(i);
}
};
//{ Driver Code Starts.
int main()
{
int t; cin >> t;
while (t--)
{
string A, B; cin >> A >> B;
Solution ob;
cout << ob.addBinary (A, B);
cout << "\n";
}
}
// Contributed By: Pranay Bansal
// } Driver Code Ends