forked from fanfank/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
add-binary.cpp
50 lines (50 loc) · 1.27 KB
/
add-binary.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
class Solution {
public:
string addBinary(string a, string b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int asz = a.size(), bsz = b.size();
int ressz = max(asz,bsz) + 3;
char *res = new char[ressz];
res[--ressz] = '\0';
int add = 0;
while(asz != 0 && bsz != 0)
{
res[--ressz] = a[--asz] + b[--bsz] - '0' + add;
if(res[ressz] >= '2')
{
add = 1;
res[ressz] -= 2;
}
else
add = 0;
}
while(asz != 0)
{
res[--ressz] = a[--asz] + add;
if(res[ressz] == '2')
{
add = 1;
res[ressz] -= 2;
}
else
add = 0;
}
while(bsz != 0)
{
res[--ressz] = b[--bsz] + add;
if(res[ressz] == '2')
{
add = 1;
res[ressz] -= 2;
}
else
add = 0;
}
if(add == 1)
res[--ressz] = '0' + add;
string s(&res[ressz]);
delete []res;
return s;
}
};