最近事情比较多,耽误了。。。。。。
Given two binary strings a
and b
, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
1 <= a.length, b.length <= 104
-
a
andb
consist only of'0'
or'1'
characters. - Each string does not contain leading zeros except for the zero itself.
利用栈来计算。
class Solution {
public:
string addBinary(string a, string b) {
stack<char> ss1;
stack<char> ss2;
stack<char> res;
for(char element:a){
ss1.push(element);
}
for(char element:b){
ss2.push(element);
}
int carry=0;
int curent=0;
int aa=0;
int bb=0;
while(!ss1.empty() || !ss2.empty()){
if(ss1.size()>0){
aa=ss1.top()-'0';
ss1.pop();
}
else{
aa=0;
}
if(ss2.size()>0){
bb=ss2.top()-'0';
ss2.pop();
}
else{
bb=0;
}
curent=(aa+bb+carry)%2;
carry=(aa+bb+carry)/2;
res.push((curent+'0'));
curent=0;
}
if(carry>0) res.push((carry+'0'));
string resul="";
while(res.size()>0){
resul+=res.top();
res.pop();
}
cout<<resul<<endl;
return resul;
}
};