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) {
int length=max(a.size(),b.size());
string temp_a;
string temp_b;
string temp_c;
int arr=0;
for(int i=a.size()-1;i>=0;i--)
if(a[i]=='1') temp_a=temp_a+"1";
else temp_a=temp_a+"0";
for(int j=b.size()-1;j>=0;j--)
if(b[j]=='1') temp_b=temp_b+"1";
else temp_b=temp_b+"0";
for(int i=a.size();i<length;i++)
temp_a=temp_a+"0";
for(int j=b.size();j<length;j++)
temp_b=temp_b+"0";
for(int i=0;i<length;i++)
{
int k=temp_a[i]-'0'+temp_b[i]-'0'+arr;
if(k==3) {temp_c=temp_c+"1";arr=1;}
else if(k==2) {temp_c=temp_c+"0";arr=1;}
else if(k==1) {temp_c=temp_c+"1";arr=0;}
else {temp_c=temp_c+"0";arr=0;}
}
if(arr==1) temp_c=temp_c+"1";
string result;
for(int i=temp_c.size()-1;i>=0;i--)
if(temp_c[i]=='1') result=result+"1";
else result=result+"0";
return result;
}
};
标签:Binary,arr,string,temp,int,Add,result,67,size From: https://blog.51cto.com/u_12504263/5718756