算法分析与设计作业题
作业来源
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”
class Solution {
public:
string addBinary(string a, string b)
{
string sum;
int carry = 0;
const int BASE = 2;
for (int i = a.size() - 1, j = b.size() - 1; i >= 0 || j >= 0;)
{
int digit1 = (i < 0) ? 0 : (a[i] - '0');
int digit2 = (j < 0) ? 0 : (b[j] - '0');
auto s = digit1 + digit2 + carry;
sum = (char) (s % BASE + '0') + sum;
carry = s / BASE;
i = (i < 0) ? i : i - 1;
j = (j < 0) ? j : j - 1;
}
if (carry > 0)
{
sum = (char) (carry + '0') + sum;
}
return sum;
}
};