67. 二进制求和
给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 1 和 0。

class Solution {
public:
string addBinary(string a, string b) {
int i = a.size() - 1, j = b.size() - 1;
int add = 0;
string res;
while (i >= 0 && j >= 0) {
int t = a[i--] - '0' + b[j--] - '0' + add;
res.push_back(t % 2 + '0');
add = t / 2;
}
while (i >= 0) {
int t = a[i--] - '0' + add;
res.push_back(t % 2 + '0');
add = t / 2;
}
while (j >= 0) {
int t = b[j--] - '0' + add;
res.push_back(t % 2 + '0');
add = t / 2;
}
if (add) res.push_back('1');
reverse(res.begin(), res.end());
return res;
}
};