[简单]#67二进制求和
题目描述
给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 1 和 0。
示例 1:
输入: a = "11", b = "1"
输出: "100"
示例 2:
输入: a = "1010", b = "1011"
输出: "10101"
提示:
每个字符串仅由字符 '0' 或 '1' 组成。
1 <= a.length, b.length <= 10^4
字符串如果不是 "0" ,就都不含前导零。
解答思路
可以以二进制加法列竖式的思路来进行,和周末做的加一题思路还挺像的?具体操作的话考虑进行反转再操作,但是这次的if else写太多了也,考虑优化一下?
具体实现
class Solution {
public:
string addBinary(string a, string b) {
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
string res = "";
char mid = '0';
int tag = max(a.length(),b.length());
for(int i=0;i<tag;i++){
if(i<a.length() && i<b.length()){
if(a[i] == '1' && b[i] == '1'){
if(mid == '1'){
res += "1";
}
else{
res += "0";
}
mid = '1';
}
else if(a[i] == '0' && b[i] == '0'){
if(mid == '1'){
res += "1";
mid = '0';
}
else{
res += "0";
}
}
else {
if(mid == '1'){
res += "0";
mid = '1';
}
else{
res += "1";
mid = '0';
}
}
}
else {
if(tag == a.length()){
if(a[i] == '0'){
if(mid == '0'){
res += "0";
}
else {
res += "1";
mid = '0';
}
}
else {
if(mid == '0'){
res += "1";
}
else {
res += "0";
mid = '1';
}
}
}else {
if(b[i] == '0'){
if(mid == '0'){
res += "0";
}
else {
res += "1";
mid = '0';
}
}
else {
if(mid == '0'){
res += "1";
}
else {
res += "0";
mid = '1';
}
}
}
}
}
if(mid == '1'){
res += "1";
}
reverse(res.begin(),res.end());
return res;
}
};
```
## 运行结果
