-
Notifications
You must be signed in to change notification settings - Fork 38
/
solve.cpp
74 lines (74 loc) · 1.45 KB
/
solve.cpp
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <string>
#include <cstdio>
#include <iostream>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
int i = a.size() - 1;
int j = b.size() - 1;
string result;
char carray = '0';
while (i >= 0 && j >= 0) {
char c = add(a[i], b[j], carray);
switch (c) {
case '0':
case '1':
carray = '0';
result.push_back(c);
break;
case '2':
carray = '1';
result.push_back('0');
break;
case '3':
carray = '1';
result.push_back('1');
break;
}
i--, j--;
}
while (i >= 0) {
char c = add(a[i], carray);
if (c == '1' || c == '0') {
result.push_back(c);
carray = '0';
} else {
result.push_back('0');
carray = '1';
}
i--;
}
while (j >= 0) {
char c = add(b[j], carray);
if (c == '1' || c == '0') {
result.push_back(c);
carray = '0';
} else {
result.push_back('0');
carray = '1';
}
j--;
}
if (carray == '1') { // 最后一位进位不要丢了
result.push_back('1');
}
return string(result.rbegin(), result.rend());
}
private:
char add(char a, char b) {
return a + b - '0';
}
char add(char a, char b, char c) {
return a + b + c - '0' - '0';
}
};
int main(int argc, char **argv)
{
Solution solution;
char a[20], b[20];
while (scanf("%s%s", a, b) != EOF) {
cout << solution.addBinary(string(a), string(b)) << endl;
}
return 0;
}