-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path67. Add Binary
44 lines (37 loc) · 940 Bytes
/
67. 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
40
41
42
43
44
class Solution {
public:
string addBinary(string a, string b) {
int n = a.size()-1;
int m = b.size()-1;
int carry=0;
string s;
while(n >= 0 || m >= 0)
{
if(n >= 0 && m >= 0)
{
int val = ((a[n] - '0') + (b[m] - '0') + carry)%2;
carry=((a[n] - '0') + (b[m] - '0') + carry)/2;
s+=(val + '0');
n--; m--;
}
else if(n >= 0)
{
int val = ((a[n] - '0') + carry)%2;
carry=((a[n] - '0') + carry)/2;
s+=(val + '0');
n--;
}
else
{
int val = ((b[m] - '0') + carry)%2;
carry=((b[m] - '0') + carry)/2;
s+=(val + '0');
m--;
}
}
if(carry > 0)
s.push_back(carry+'0');
reverse(s.begin(), s.end());
return s;
}
};