string addBinary(string a, string b) {
int N = a.size(), M = b.size(), K = max(N, M);
string res(K, ' ');
int carry = 0;
int i = N-1, j = M-1, k = K-1;
while (i >= 0 || j >= 0)
{
int sum = carry;
if (i >= 0) sum += a[i--] - '0';
if (j >= 0) sum += b[j--] - '0';
carry = sum / 2;
res[k--] = sum % 2 + '0';
}
if (carry == 1)
res.insert(res.begin(), '1');
return res;
}
No comments:
Post a Comment