-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd_Binary.cpp
More file actions
37 lines (37 loc) · 1 KB
/
Add_Binary.cpp
File metadata and controls
37 lines (37 loc) · 1 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
/*
O(max(M,N))
O(max(M,N))
*/
class Solution {
public:
string addBinary(string a, string b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(a.size()<b.size())
{
string tmp=a;
a=b;
b=tmp;
}
vector<char> res;
int carry=0;
int i=a.size()-1,j=b.size()-1;
while(j>=0)
{
res.push_back((a[i]-'0'+b[j]-'0'+carry)%2+'0');
carry=(a[i]-'0'+b[j]-'0'+carry)/2;
i--;
j--;
}
while(i>=0)
{
res.push_back((a[i]-'0'+carry)%2+'0');
carry=(a[i]-'0'+carry)/2;
i--;
}
if(carry)
res.push_back('1');
reverse(res.begin(),res.end());
return string(res.begin(),res.end());
}
};