title: Daily Practice (39): Binary Summation
categories:[Swords offer]
tags:[Daily practice]
date: 2022/04/11
Daily practice (39): Binary summation
Given two binary strings, return their sum (in binary).
The input is a non-empty string and contains only the numbers 1 and 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
hint:
Each string consists only of the characters '0' or '1'.
1 <= a.length, b.length <= 10^4
Strings do not contain leading zeros unless they are "0".
Source: LeetCode
Link: https://leetcode-cn.com/problems/add-binary
Method 1: Simulation operation
Thought analysis
Simulate direct calculation, that is, according to a similar decimal calculation method, considering the carry
string addBinary(string a, string b) {
// 先倒序
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int na = a.size();
int nb = b.size();
int n = max(na, nb);
string res = "";
int curr = 0;
for (int i = 0; i < n; ++i)
{
curr += i < na ? a[i] == '1' : 0;
curr += i < nb ? b[i] == '1' : 0;
res.push_back(curr % 2 ? '1' : '0');
curr /= 2;
}
if (curr)
{
res.push_back('1');
}
reverse(res.begin(), res.end());
return res;
}
Method 2: Simulation operation optimization (LeetCode English website boss writing)
Thought analysis
Simulate direct calculation, that is, according to a similar decimal calculation method, considering the carry
string addBinary(string a, string b) {
string s;
s.reserve(a.size() + b.size());
int c = 0, i = a.size() - 1, j = b.size() - 1;
while(i >= 0 || j >= 0 || c == 1)
{
c += i >= 0 ? a[i--] - '0' : 0;
c += j >= 0 ? b[j--] - '0' : 0;
s.push_back((c & 1) + '0');
c >>= 1;
}
reverse(s.begin(), s.end());
return s;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。