-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
30 lines (26 loc) · 858 Bytes
/
main.cpp
File metadata and controls
30 lines (26 loc) · 858 Bytes
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
#include <string>
using namespace std;
class Solution
{
public:
string addBinary(string a, string b)
{
string s = ""; // solution empty string
// read 'a' & 'b' from end to start (like normal bit sum)
// c represet the sum and the carry at the same time
int c = 0, i = a.size() - 1, j = b.size() - 1;
// while 'a' & 'b' are not read at all or there is a carry
while (i >= 0 || j >= 0 || c == 1)
{
// map '1' or '0' to int and sum up to 'c'
// reduce i & j. If i < j or j < i fill gap with zeros
c += i >= 0 ? a[i--] - '0' : 0;
c += j >= 0 ? b[j--] - '0' : 0;
// remap to char and concatenate to solution
s = char(c % 2 + '0') + s;
// calculate carry
c /= 2;
}
return s;
}
};