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^4
- Each string is either
"0"
or doesn’t contain any leading zero.
题意:对两个二进制字符串进行加法运算。
思路:先翻转 a
和 b
,然后从头开始相加即可。不过下面的代码写得太过繁琐了。emmm,其实可以不必翻转,也不必写后面两个循环。等有时间了,更新一下。先打卡再说。
代码:
class Solution {
public:
string addBinary(string a, string b) {
string c;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int size = min(a.size(), b.size()), carry = 0;
for (int i = 0; i < size; ++i) {
int x = a[i] - '0', y = b[i] - '0', z = x + y + carry;
c.push_back(z % 2 + '0');
carry = z / 2;
}
for (int i = size; i < a.size(); ++i) {
int k = a[i] - '0' + carry;
c.push_back(k % 2 + '0');
carry = k / 2;
}
for (int i = size; i < b.size(); ++i) {
int k = b[i] - '0' + carry;
c.push_back(k % 2 + '0');
carry = k / 2;
}
if (carry) c.push_back(carry + '0');
reverse(c.begin(), c.end());
return c;
}
};
效率:
执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗:6.6 MB, 在所有 C++ 提交中击败了100.00% 的用户