-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet_0067_add_binary__Carry.cc
More file actions
66 lines (63 loc) · 1.43 KB
/
leet_0067_add_binary__Carry.cc
File metadata and controls
66 lines (63 loc) · 1.43 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
class Solution {
public:
string addBinary(string a, string b)
{
int lena = a.length();
int lenb = b.length();
int diff = abs(lena - lenb);
int len = max(lena , lenb);
int carry, i ;
string ones = "";
string E = "";
string s = "";
string r = "";
i = -1;
while (++i < diff)
s += '0';
if (lena ^ len)
a = s + a;
if (lenb ^ len)
b = s + b;
i = -1;
while (++i < len)
E += a[i] + b[i] - '0';
carry = 0;
i = len ;
while (--i > -1)
{
char c = E[i];
if (c == '0')
{
if (!carry) r += '0';
else
{
carry -- ;
r += '1';
}
}
if (c == '1')
{
if (!carry) r += '1';
else r += '0';
}
if (c == '2')
{
if (!carry)
{
carry ++ ;
r += '0';
}
else
r += '1';
}
}
if (carry)
{
i = -1;
while (++i < carry)
ones += '1';
}
reverse(r.begin(), r.end());
return ones + r ;
}
};