题目:
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"
描述:
给出两个二进制串,输出两个二进制数的和,结果用二进制表示
分析:
模拟大数加法,只不过是二进制下而已
代码:(时间和空间复杂度均为 O(n),虽然空间复杂度能优化到 O(1),不过没必要继续优化)
class Solution {
public:
string addBinary(string a, string b) {
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
string result;
int carry = 0, i = 0, j = 0;
while (carry || i < a.size() || j < b.size()) {
int temp = carry;
if (i < a.size()) {
temp += a[i] - '0';
}
if (j < b.size()) {
temp += b[j] - '0';
}
carry = temp / 2;
temp %= 2;
result.push_back(temp + '0');
++i, ++j;
}
reverse(result.begin(), result.end());
return result;
}
};