Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.Solution:
string addBinary(string a, string b) {
int lenA = a.size()-1;
int lenB = b.size()-1;
int carry = 0;
string result = "";
while(lenA>=0||lenB>=0)
{
int cura = 0;
if(lenA>=0)
cura = a[lenA] - '0';
int curb =0;
if(lenB>=0)
curb = b[lenB] - '0';
int cur = cura+curb+carry;
if(cur>1)
{
carry = 1;
cur = cur - 2;
}
else
carry = 0;
result+=char('0' + cur);
lenA--;
lenB--;
}
if(carry>0)
result+='1';
int start = 0;
int end = result.size()-1;
while(start<end)
{
char tmp = result[start];
result[start] = result[end];
result[end] =tmp;
start++;
end--;
}
return result;
}
No comments:
Post a Comment