-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path67.add-binary.cpp
More file actions
72 lines (63 loc) · 1.76 KB
/
67.add-binary.cpp
File metadata and controls
72 lines (63 loc) · 1.76 KB
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
#include "testharness.h"
#include <map>
#include <string>
#include <string.h>
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
string& first = a.size() > b.size() ? a : b;
string& second = a.size() > b.size() ? b : a;
int rs = first.size();
int ts = second.size();
bool hasCarryOn = false;
while (ts >= 0) {
if (first[rs] == '1') {
if (second[ts] == '1') {
if (!hasCarryOn) {
first[rs] = '0';
hasCarryOn = true;
}
} else {
if (hasCarryOn) {
first[rs] = '0';
}
}
} else {
if (second[ts] == '1') {
first[rs] = hasCarryOn ? '0' : '1';
} else {
if (hasCarryOn) {
first[rs] = '1';
hasCarryOn = false;
}
}
}
rs--;
ts--;
}
for (; rs >= 0; rs--) {
if (first[rs] == '1') {
if (hasCarryOn) {
first[rs] = '0';
} else {
break;
}
} else {
if (hasCarryOn) {
first[rs] = '1';
hasCarryOn = false;
}
break;
}
}
return hasCarryOn ? "1" + first : first;
}
};
TEST(Solution, test) {
ASSERT_EQ("100", addBinary("11", "1"));
ASSERT_EQ("100", addBinary("1", "11"));
ASSERT_EQ("110", addBinary("11", "11"));
}