Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
My Submitted Code
class Solution {
public:
string addBinary(string a, string b) {
int lena=a.size();
int lenb=b.size();
string result;
stack<char> stk;
char carr='0';
lena--;
lenb--;
while(lena>=0 || lenb>=0){
char ca='0';
char cb='0';
if(lena>=0){
ca=a.at(lena);
}
if(lenb>=0){
cb=b.at(lenb);
}
if(ca == '0' && cb== '0'){
if(carr == '1'){
stk.push('1');
}else
stk.push('0');
carr='0';
}
else if((ca =='0' && cb == '1') ||
(ca == '1' && cb == '0')){
if(carr == '1'){
stk.push('0');
carr='1';
}else{
stk.push('1');
carr='0';
}
}
else if(ca == '1' && cb == '1'){
if(carr == '1'){
stk.push('1');
}else{
stk.push('0');
}
carr='1';
}
--lena;
--lenb;
}
if(carr == '1'){
stk.push('1');
}
while(!stk.empty()){
result.push_back(stk.top());
stk.pop();
}
return result;
}
};