-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add Binary Strings
81 lines (45 loc) Β· 959 Bytes
/
Add Binary Strings
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
//User function template for C++
class Solution{
public:
string addBinary(string A, string B)
{
// your code here
string ans="";
int carry=0;
int i=A.size()-1,j=B.size()-1;
while(i>=0 && j>=0){
int t=A[i]-'0'+B[j]-'0'+carry;
ans+=to_string(t%2);
carry=t/2;
i--;
j--;
}
while(i>=0){
int t=A[i]-'0'+carry;
ans+=to_string(t%2);
carry=t/2;
i--;
}
while(j>=0){
int t=B[j]-'0'+carry;
ans+=to_string(t%2);
carry=t/2;
j--;
}
if(carry)
ans+=to_string(carry);
reverse(ans.begin(),ans.end());
string res="";
int idx=-1;
for(int i=0;i<ans.length();i++){
if(ans[i]!='0'){
idx=i;
break;
}
}
for(int i=idx;i<ans.length();i++){
res+=ans[i];
}
return res;
}
};