###### zkj126521的博客

Given two binary strings, return their sum (also a binary string).

For example,
a = “11”
b = “1”
Return “100”.

class Solution {
public:
string addBinary(string a, string b) {
int c = 0, quo = 0, i, j;
string ans;
for(i = a.length() - 1, j = b.length() - 1; i >= 0 || j >= 0; --i, --j){
if(i >= 0 && j >= 0){
quo = (a[i] - '0' + b[j] - '0' + c) % 2;
c = (a[i] - '0' + b[j] - '0' + c) / 2;
} else if(i >= 0){
quo = (a[i] - '0' + c) % 2;
c = (a[i] - '0' + c) / 2;
} else if(j >= 0){
quo = (b[j] - '0' + c) % 2;
c = (b[j] - '0' + c) / 2;
}
ans.insert(ans.begin(), (quo + '0'));
}

if(c != 0)
ans.insert(ans.begin(), (c + '0'));
return ans;
}
};

class Solution {
public:
string addBinary(string a, string b) {
string res;
int i, j, carry = 0;
for(i = a.length() - 1, j = b.length() - 1; i >= 0 && j >= 0; --i, --j){
res.push_back((a[i] - '0' + b[j] - '0' + carry) % 2 + '0');
carry = (a[i] - '0' + b[j] - '0' + carry) / 2;
}
while(i >= 0){
res.push_back((a[i] - '0' + carry) % 2 + '0');
carry = (a[i] - '0' + carry) / 2;
--i;
}
while(j >= 0){
res.push_back((b[j] - '0' + carry) % 2 + '0');
carry = (b[j] - '0' + carry) /  2;
--j;
}
if(carry) res.push_back('1');

string rev;
int len = res.length();
for(i = len - 1; i >= 0; --i){
rev.push_back(res[i]);
}
return rev;
}
};

#### Add Binary | leetcode 67 【Java解题报告】

2015-10-04 14:23:39

#### leetcode 67 Add Binary C++

2016-06-13 10:54:12

2015-07-05 21:49:19

2015-08-19 20:58:22

#### 【leetcode】67. Add Binary（Python & C++）

2017-09-04 20:18:41

2014-11-06 21:36:03

2017-07-17 20:22:34

#### LeetCode 67 : Add Binary (Java)

2015-12-03 21:08:20

#### 67. Add Binary [easy] (Python)

2016-06-18 17:29:55

2016-01-18 21:49:14