Working C++ Solution


#1
string Solution::addBinary(string A, string B) {
string s,l, ans="";
stack<char>stk;
if(A.length() > B.length()){
    l = A; s = B;
}
else{
    l = B; s = A;
}

int sl = s.length(), ll = l.length();
int c = 0, li = ll-1;

for(int i=sl-1; i>=0; i--){
    int sum = c + (s[i]-'0') + (l[li]-'0'); li--;
    
    if(sum==0){
        stk.push('0'); c=0;
    }
    else if(sum==1){
        stk.push('1'); c=0;
    }
    else if(sum==2){
        stk.push('0'); c=1;
    }
    else if(sum==3){
        stk.push('1'); c=1;
    }
}

for(int i=li; i>=0; i--){
    int sum = c + (l[i]-'0');
    if(sum==0){
        stk.push('0'); c=0;
    }
    else if(sum==1){
        stk.push('1'); c=0;
    }
    else if(sum==2){
        stk.push('0'); c=1;
    }
}

if(c)
    stk.push('1');
    
while(!stk.empty()){
    ans.push_back(stk.top());
    stk.pop();
}
return ans;

}