Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0 .
Example 1:
Input: a = "11", b = "1" Output: "100"Example 2:
Input: a = "1010", b = "1011" Output: "10101"Constraints:
Each string consists only of '0' or '1' characters.1 <= a.length, b.length <= 10^4Each string is either "0" or doesn’t contain any leading zero.题意:给出两个二进制字符串,返回它们的和(用二进制表示)。
和 LeetCode 2. Add Two Numbers 完全一致:
class Solution { public: string addBinary(string a, string b) { string c; int n = a.size(), m = b.size(), i = n - 1, j = m - 1, carry = 0; while (i >= 0 || j >= 0) { int sum = carry; if (i >= 0) { sum += a[i] - '0'; --i; } if (j >= 0) { sum += b[j] - '0'; --j; }; c.push_back(sum % 2 + '0'); carry = sum / 2; } if (carry) c.push_back(carry + '0'); reverse(c.begin(), c.end()); return c; } };效率如下:
执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户 内存消耗:6.2 MB, 在所有 C++ 提交中击败了98.07% 的用户