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) {
b = string(na - nb, '0') + b;
} else {
a = string(nb - na, '0') + a;
}
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;
}
return carry == 1 ? "1" + res : 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

LeetCode All in One 题目讲解汇总(持续更新中…)

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation