# [LeetCode] 67. Add Binary 二进制数相加

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 and b 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) {
string res;
int na = a.size(), nb = b.size(), n = max(na, nb), carry = 0;
if (na > nb) {
for (int i = 0; i < na - nb; ++i) b.insert(b.begin(), '0');
} else {
for (int i = 0; i < nb - na; ++i) a.insert(a.begin(), '0');
}
for (int i = n - 1; i >= 0; --i) {
int sum = (a[i] - '0') + (b[i] - '0') + carry;
res = to_string(sum % 2) + res;
carry = sum / 2;
}
if (carry) res.insert(res.begin(), '1');
return res;
}
};

class Solution {
public:
string addBinary(string a, string b) {
string res = "";
int m = a.size() - 1, n = b.size() - 1, carry = 0;
while (m >= 0 || n >= 0) {
int p = m >= 0 ? a[m--] - '0' : 0;
int q = n >= 0 ? b[n--] - '0' : 0;
int sum = p + q + carry;
res = to_string(sum % 2) + res;
carry = sum / 2;
}
return carry == 1 ? "1" + res : res;
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/67

Multiply Strings

Plus One