leetCode67.AddBinary字符串-创新互联
67. Add Binary

Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
思路:
1.将两个字符串按数组相加得到新数组。
2.将新数组转换成结果。
代码如下:
class Solution {
public:
string addBinary(string a, string b) {
int sizeA = a.size();
int sizeB = b.size();
int carry = 0;
vector result;
string resultStr;
if (sizeA < sizeB)
return addBinary(b, a);
for (int i = 0; i < sizeB; i++)
{
int cur = (a[sizeA - i - 1] - '0') + (b[sizeB - i - 1] - '0') + carry;
if (cur < 2)
{
result.push_back(cur);
carry = 0;
}
else if (cur == 2)
{
result.push_back(0);
carry = 1;
}
else if (cur == 3)
{
result.push_back(1);
carry = 1;
}
}
for (int j = sizeB; j < sizeA; j++)
{
int cur = (a[sizeA - j - 1] - '0') + carry;
if (cur < 2)
{
result.push_back((a[sizeA - j - 1] - '0') + carry);
carry = 0;
}
else if (cur == 2)
{
result.push_back(0);
carry = 1;
}
else if (cur == 3)
{
result.push_back(1);
carry = 1;
}
}
if (carry == 2)
{
result.push_back(0);
result.push_back(1);
}
else if ( carry == 1)
{
result.push_back(1);
}
for (int k = 0; k < result.size(); k++)
{
if (result[result.size() - 1 - k] == 1)
{
resultStr.append(1, '1');
}
else
{
resultStr.append(1, '0');
}
}
return resultStr;
}
}; 2016-08-10 23:39:26
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
网页名称:leetCode67.AddBinary字符串-创新互联
文章出自:http://lzwzjz.cn/article/dejcdp.html


咨询
建站咨询
