-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd Binary
39 lines (32 loc) · 1.02 KB
/
Add Binary
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
class Solution {
public:
string addBinary(string a, string b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int lena = a.size(), lenb = b.size();
string &longer = (lena>=lenb)?a:b, &shorter = (lena<lenb)?a:b, res;
longer.insert(longer.begin(), '0');
for (int i=0; i<=abs(lenb-lena); ++i)
shorter.insert(shorter.begin(), '0');
lena = max(lena, lenb)+1;
int carry = 0;
for (int i=lena-1; i>=0; --i)
{
int tmpa = a[i]-'0', tmpb = b[i]-'0';
int sum = tmpa+tmpb+carry;
tmpa = sum%2;
carry = sum/2;
res.insert(res.begin(), '0'+tmpa);
}
carry = 0;
for (int i=0; i<lena; ++i)
{
if (res[i] == '0')
++carry;
else
break;
}
res.erase(0, carry);
return (res=="")?"0":res;
}
};