题目链接:https://leetcode.cn/problems/add-binary/
思路如下:
高精度加法,从低位到高位逐个对应相加。
C++代码如下:
class Solution {
public:
string addBinary(string a, string b) {
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int lena = a.size(), lenb = b.size();
string res;
// 高精度加法
for (int i = 0, t = 0; i < lena || i < lenb || t != 0; ++i) {
if (i < lena) t += a[i] - '0';
if (i < lenb) t += b[i] - '0';
res += char(t % 2 + '0');
t /= 2;
}
reverse(res.begin(), res.end());
return res;
}
};