leetcode-----67. 二进制求和
代码
class Solution {
public:
string addBinary(string a, string b) {
if (a.size() < b.size()) swap(a, b);
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int t = 0, k = 0;
string ans;
while (k < b.size()) {
t += a[k] - '0' + b[k] - '0';
ans += to_string(t & 1);
t /= 2;
k++;
}
while (k < a.size()) {
t += a[k] - '0';
ans += to_string(t & 1);
t /= 2;
k++;
}
if (t) ans += '1';
reverse(ans.begin(), ans.end());
return ans;
}
};