LeetCode 0067 - Add Binary
# Hints
- 水题
# 题面
Difficulty | Time Complexity Limit | Extra-Memory Complexity Limit |
---|---|---|
Easy |
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"
Constraints:
Each string consists only of
'0'
or'1'
characters.Each string is either
"0"
or doesn't contain any leading zero.
# 题意
给定两个字符串表示的二进制数,求它们的和。输入保证不含前导零(除 本身以外)。
# 题解
水题。
# AC代码
class Solution {
public:
string addBinary(const string & a, const string & b) {
// 初始化
int n = a.length(), m = b.length();
if (n < m) {
return addBinary(b, a);
}
// 求解
string res;
int rem = 0;
for (int i = 1; i <= n; i ++) {
int sum = (a[n - i] - '0') + (i <= m ? (b[m - i] - '0') : 0) + rem;
rem = sum / 2;
res += ((sum % 2) + '0');
}
if (rem > 0) {
res += (rem + '0');
}
// 返回
reverse(res.begin(), res.end());
return res;
}
};
- 01
- Reading Papers - Kernel Concurrency06-01
- 02
- Linux Kernel - Source Code Overview05-01
- 03
- Linux Kernel - Per-CPU Storage05-01