题目:
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) {
int lena = a.length();
int lenb = b.length();
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
vector<int> res;
int pos = 0;
while(pos < lena && pos < lenb)
res.push_back(a[pos] - '0' + b[pos++] - '0');
while(pos < lena)
res.push_back(a[pos++] - '0');
while(pos < lenb)
res.push_back(b[pos++] - '0');
int carry = 0;
for(int i = 0;i < res.size(); ++i)
{
int t = res[i];
res[i] = (res[i] + carry) % 2;
carry = (t + carry) / 2;
}
if(carry)
res.push_back(carry);
string str = "";
for(int i = 0;i < res.size();++i)
{
str += (res[i] + '0');
}
reverse(str.begin(),str.end());
return str;
}
};
和大整数加法一样的思想