时间轴

2025-11-25

init


题目:

注意最后一位进位

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <string>
#include <algorithm>
using std::string;

class Solution {
public:
string addBinary(string a, string b)
{
int i = a.size() - 1, j = b.size() - 1;
int carry = 0;
int curr_a_bit, curr_b_bit, curr_sum;
string res;
while (i >= 0 || j >= 0) {
if (i < 0) {
curr_a_bit = 0;
} else {
curr_a_bit = a[i] - '0';
i--;
}
if (j < 0) {
curr_b_bit = 0;
} else {
curr_b_bit = b[j] - '0';
j--;
}

curr_sum = carry + curr_a_bit + curr_b_bit;
carry = curr_sum / 2;
res.push_back('0' + curr_sum % 2);
}
if (carry == 1) {
res.push_back('1');
}
std::reverse(res.begin(), res.end());
return res;
}
};
int main()
{
Solution S;
S.addBinary("11", "1");
}