67. Add Binary
Problem:
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
思路:
Solution (C++):
string addBinary(string a, string b) {
int m = a.size(), n = b.size(), carry = 0, i = 0, digit = 0;
vector<int> v;
while (i < m && i < n) {
digit = int(a[m-1-i]) -48 + int(b[n-1-i]) -48 + carry;
carry = digit / 2;
digit %= 2;
v.push_back(digit);
++i;
}
if (i < m) {
while (i < m) {
digit = int(a[m-1-i]) -48 + carry;
carry = digit / 2;
digit %= 2;
v.push_back(digit);
++i;
}
}
if (i < n) {
while (i < n) {
digit = int(b[n-1-i]) -48 + carry;
carry = digit / 2;
digit %= 2;
v.push_back(digit);
++i;
}
}
if (carry == 1) v.push_back(carry);
string res = "";
for (int j = 0; j < v.size(); ++j) {
res += to_string(v[v.size()-j-1]);
}
return res;
}
性能:
Runtime: 4 ms Memory Usage: 6.8 MB
思路:
Solution (C++):
性能:
Runtime: ms Memory Usage: MB
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
![](https://www.cnblogs.com/images/cnblogs_com/dysjtu1995/1468066/t_qrcode_for_gh_547d3edeac81_258.jpg)
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。