[LeetCode] 67. Add Binary
题目链接:传送门
Description
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Solution
题意:
二进制加法
思路:
按位加,处理进位
class Solution {
public:
string addBinary(string a, string b) {
string res = "";
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int i = 0, j = 0, add = 0, alen = a.length(), blen = b.length();
while (i < alen || i < blen || add) {
add += i < alen ? a[i] - '0' : 0;
add += i < blen ? b[i] - '0' : 0;
res.append(to_string(add % 2));
add /= 2;
i++;
}
reverse(res.begin(), res.end());
return res;
}
};