# 二进制求和

给你两个二进制字符串,返回它们的和(用二进制表示)。

输入为 非空 字符串且只包含数字 1 和 0

 

示例 1:

输入: a = "11", b = "1"
输出:
"100"

示例 2:

输入: a = "1010", b = "1011"
输出:
"10101"

 

提示:

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; string a = "1010"; string b = "1011"; string res; res = sol.addBinary(a, b); cout << res; return 0; } ``` ## 答案 ```cpp class Solution { public: string addBinary(string a, string b) { string res; int carry = 0; int m = a.size() - 1, n = b.size() - 1; while (m >= 0 || n >= 0) { int q = (m >= 0) ? a[m] - '0' : 0; int p = (n >= 0) ? b[n] - '0' : 0; int k = q + p + carry; res = to_string(k % 2) + res; carry = k / 2; } if (1 == carry) res = '1' + res; return res; } }; ``` ## 选项 ### A ```cpp class Solution { public: string addBinary(string a, string b) { long aa = 0, bb = 0; long sum = 0; string res; int p = 0; stringstream outa(a); stringstream outb(b); outa >> aa; outb >> bb; sum = aa + bb; bool flag = false; while (sum != 0) { p = sum % 10; if (flag == true) p++; flag = false; sum /= 10; if (p == 0) res = res + "0"; else if (p % 2 == 0) { flag = true; res = res + "0"; } else res = res + "1"; } if (res[res.size() - 1] == '0') res = res + "1"; reverse(res.begin(), res.end()); return res; } }; ``` ### B ```cpp class Solution { public: string addBinary(string a, string b) { if (b.size() > a.size()) { string temp = b; b = a; a = temp; } int i = a.size() - 1; int j = b.size() - 1; if (i != j) { for (int k = 0; k < i - j; k++) b = "0" + b; } int count = 0; for (int k = i; k >= 0; k--) { if (a[k] - '0' + b[k] - '0' + count == 0) { a[k] = '0'; count = 0; } else if (a[k] - '0' + b[k] - '0' + count == 1) { a[k] = '1'; count = 0; } else if (a[k] - '0' + b[k] - '0' + count == 3) { a[k] = '1'; count = 1; } else { a[k] = '0'; count = 1; } } if (count == 1) a = '1' + a; return a; } }; ``` ### C ```cpp class Solution { public: string addBinary(string a, string b) { string result = "", rr = ""; char aa, bb; int l1 = a.length(), l2 = b.length(), i = l1 - 1, j = l2 - 1, carry = 0, sum = 0; while (true) { if (i < 0) aa = '0'; else aa = a[i]; if (j < 0) bb = '0'; else bb = b[j]; sum = (aa - '0') + (bb - '0') + carry; result += ((sum % 2) + '0'); carry = sum / 2; j--; i--; if (i < 0 && j < 0) { if (carry == 1) result += "1"; break; } } int l3 = result.length(); for (int i = l3 - 1; i >= 0; i--) rr += result[i]; return rr; } }; ```