题目描述:给定两个二进制字符串,返回他们的和(用二进制表示)。输入为非空字符串且只包含数字 1
和 0
。
string addBinary(string a, string b) {
stack<char> s_a,s_b;
for(int i = 0;i<a.size();++i){
s_a.push(a[i]);
}
for(int i = 0;i<b.size();++i){
s_b.push(b[i]);
}
int jinwei = 0;
stack<char> ans;
while(!s_a.empty()&&!s_b.empty()){
int re_wei = s_a.top()-'0'+s_b.top()-'0'+jinwei;
if(re_wei<=1) {
char s = re_wei+'0';
ans.push(s);
jinwei = 0;
}
else if(re_wei<3){
ans.push('0');
jinwei = 1;
}
else{
ans.push('1');
jinwei = 1;
}
s_a.pop();
s_b.pop();
}
if(s_a.empty()&&!s_b.empty()){
while(!s_b.empty()){
int re_wei = s_b.top()-'0'+jinwei;
if(re_wei<=1) {
char s = re_wei+'0';
ans.push(s);
jinwei = 0;
}
else{
ans.push('0');
jinwei = 1;
}
s_b.pop();
}
}
else if(!s_a.empty()&&s_b.empty()){
while(!s_a.empty()){
int re_wei = s_a.top()-'0'+jinwei;
if(re_wei<=1) {
char s = re_wei+'0';
ans.push(s);
jinwei = 0;
}
else{
ans.push('0');
jinwei = 1;
}
s_a.pop();
}
}
if(jinwei==1) ans.push('1');
string add;
while(!ans.empty()){
add+=ans.top();
ans.pop();
}
return add;
}
各种if判断,用了stack空间换时间。题解中对短字符进行补长操作
执行用时 :4 ms, 在所有 cpp 提交中击败了90.23%的用户
内存消耗 :9.3 MB, 在所有 cpp 提交中击败了8.74%的用户