forked from iphkwan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add_Binary.cc
48 lines (48 loc) · 1.23 KB
/
Add_Binary.cc
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
class Solution {
public:
string addBinary(string a, string b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
string ans = "";
int pa = a.length() - 1;
int pb = b.length() - 1;
int nxt = 0, cur;
while (pa >= 0 && pb >= 0) {
cur = a[pa] + b[pb] + nxt - '0' - '0';
if (cur >= 2) {
cur -= 2;
nxt = 1;
} else {
nxt = 0;
}
ans = char(cur + '0') + ans;
pa--, pb--;
}
while (pa >= 0) {
cur = a[pa] + nxt - '0';
if (cur >= 2) {
cur -= 2;
nxt = 1;
} else {
nxt = 0;
}
ans = char(cur + '0') + ans;
pa--;
}
while (pb >= 0) {
cur = b[pb] + nxt - '0';
if (cur >= 2) {
cur -= 2;
nxt = 1;
} else {
nxt = 0;
}
ans = char(cur + '0') + ans;
pb--;
}
if (nxt) {
ans = '1' + ans;
}
return ans;
}
};