Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
class Solution
{
public:
string addBinary(string a, string b)
{
string s = "";
int c = 0, i = a.size() - 1, j = b.size() - 1;
while(i >= 0 || j >= 0 || c == 1)
{
c += i >= 0 ? a[i --] - '0' : 0;
c += j >= 0 ? b[j --] - '0' : 0;
s = char(c % 2 + '0') + s;
c /= 2;
}
return s;
}
};
本文介绍了一种算法,用于将两个二进制字符串相加并返回其和,该和同样为二进制字符串形式。通过迭代两个输入字符串的每一位,并使用简单的位运算来处理进位,最终得到正确的结果。
714

被折叠的 条评论
为什么被折叠?



