0%

67. Add Binary

O(max(m, n)) time O(1) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
string addBinary(string a, string b) {
string res;
for (int c = 0, i = a.length() - 1, j = b.length() - 1;
i >= 0 || j >= 0 || c > 0;
--i, --j) {
int x = i < 0 ? 0 : (a[i] - '0');
int y = j < 0 ? 0 : (b[j] - '0');
int s = x + y + c;
res += '0' + (s & 1);
c = s >> 1;
}
return string(rbegin(res), rend(res));
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
string addBinary(string a, string b) {
if (a.empty()) return b;
if (b.empty()) return a;
int c = 0;
string res;
while (!a.empty() || !b.empty() || c > 0) {
int x = a.empty() ? 0 : (a.back() - '0');
int y = b.empty() ? 0 : (b.back() - '0');
if (!a.empty()) {
a.pop_back();
}
if (!b.empty()) {
b.pop_back();
}
int s = x + y + c;
res += '0' + (s & 1);
c = (s >> 1);
}
return string(rbegin(res), rend(res));
}
};