class Solution {
public:
string addBinary(string a, string b) {
if (a.size() < b.size()) return addBinary(b, a);
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int jin = 0, L = b.size(), i = 0;
for (; i < L; ++i) {
int t = jin + a[i] + b[i] - '0' - '0';
a[i] = t % 2 + '0';
jin = t / 2;
}
while (i < a.size() && jin == 1) {
int t = jin + a[i] - '0';
a[i] = t % 2 + '0';
jin = t / 2;
++i;
}
if (jin == 1) a.push_back('1');
reverse(a.begin(), a.end());
return a;
}
};
Leetcode 67. 二进制求和
最新推荐文章于 2022-04-07 15:58:48 发布