Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
这道题并不复杂,需要注意的是要从后往前遍历a,b求和,同时要有一个进位项,对各种情况都要分析到:
string addBinary(string a, string b) {
string ans;
if(a.size()==0) return b;
if(b.size()==0) return a;
int plus=0;
int a1=a.size()-1;
int b1=b.size()-1;
while(a1!=-1||b1!=-1){
if(a1!=-1&&b1!=-1){
if(a[a1]=='1'&&b[b1]=='1'&&plus==1) { ans.append("1");plus=1;}
else if(a[a1]=='1'&&b[b1]=='1'&&plus==0) { ans.append("0");plus=1;}
else if(a[a1]=='0'&&b[b1]=='0'&&plus==1) { ans.append("1");plus=0;}
else if(a[a1]=='0'&&b[b1]=='0'&&plus==0) { ans.append("0");plus=0;}
else if(plus==0) { ans.append("1");plus=0;}
else { ans.append("0");plus=1; }
a1--;b1--;
}else if(a1==-1&&b1!=-1){
if(b[b1]=='1'&&plus==1) { ans.append("0");plus=1;}
else if(b[b1]=='0'&&plus==0) { ans.append("0");plus=0;}
else { ans.append("1");plus=0;}
b1--;
}else if(a1!=-1&&b1==-1){
if(a[a1]=='1'&&plus==1) { ans.append("0");plus=1;}
else if(a[a1]=='0'&&plus==0) { ans.append("0");plus=0;}
else { ans.append("1");plus=0;}
a1--;
}
}
if(plus==1) ans.append("1");
reverse ( ans.begin(), ans.end () );
return ans;
}
可以看到比较繁琐,进行优化,结果如下:
string addBinary(string a, string b) {
string ans;
if(a.size()==0) return b;
if(b.size()==0) return a;
int plus=0;
int a1=a.size()-1;
int b1=b.size()-1;
while(a1!=-1||b1!=-1){
if(a1!=-1&&b1!=-1){
int i=a[a1]-'0'+b[b1]-'0'+plus;
ans.append(std::to_string(i%2));plus=i/2;
a1--;b1--;
}else if(a1==-1&&b1!=-1){
int i=b[b1]-'0'+plus;
ans.append(std::to_string(i%2));plus=i/2;
b1--;
}else if(a1!=-1&&b1==-1){
int i=a[a1]-'0'+plus;
ans.append(std::to_string(i%2));plus=i/2;
a1--;
}
}
if(plus==1) ans.append("1");
reverse(ans.begin(),ans.end());
return ans;
}