Given two binary strings, return their sum (also a binary string).
For example,
a ="11"
b ="1"
Return"100".
思路很简单,先把短的字符串补齐,然后逐位相加。 string addBinary(string a, string b) { int length = max(a.size(), b.size()); string res(length + 1, ' '); char flag = '0'; while (length > a.size()) { a = "0" + a; } while (length > b.size()) { b = "0" + b; } for (int i = length - 1; i >= 0; --i) { int ch = a[i] + b[i] + flag - 3 * '0'; if (ch == 3) { res[i + 1] = '1'; flag = '1'; } else if (ch == 2) { res[i + 1] = '0'; flag = '1'; } else { res[i + 1] = ch + '0'; flag = '0'; } } if (flag == '1') res[0] = '1'; else res = res.substr(1); return res; }