-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode067_Add_Binary.cpp
More file actions
105 lines (100 loc) · 2.52 KB
/
LeetCode067_Add_Binary.cpp
File metadata and controls
105 lines (100 loc) · 2.52 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
class Solution {
public:
string addBinary(string a, string b) {
string result;
int count_a = a.size();
int count_b = b.size();
int i, j;
bool carry_flag = 0;
for(i = count_a-1, j = count_b-1; i >= 0 && j >= 0; i--, j--)
{
if(a[i] != b[j])
{
if(carry_flag)
{
carry_flag = 1;
result.push_back('0');
}
else
{
carry_flag = 0;
result.push_back('1');
}
}
else if(a[i] == '1')
{
if(carry_flag)
{
result.push_back('1');
}
else
{
result.push_back('0');
}
carry_flag = 1;
}
else
{
if(carry_flag)
{
result.push_back('1');
}
else
{
result.push_back('0');
}
carry_flag = 0;
}
}
if(count_a > count_b)
{
for(int m = count_a-count_b-1; m >= 0; m--)
{
if(carry_flag)
{
if(a[m] == '1')
{
result.push_back('0');
}
else
{
carry_flag = 0;
result.push_back('1');
}
}
else
{
result.push_back(a[m]);
}
}
}
else
{
for(int m = count_b-count_a-1; m >= 0; m--)
{
if(carry_flag)
{
if(b[m] == '1')
{
result.push_back('0');
}
else
{
carry_flag = 0;
result.push_back('1');
}
}
else
{
result.push_back(b[m]);
}
}
}
if(carry_flag)
{
result.push_back('1');
}
reverse(result.begin(), result.end());
return result;
}
};