-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAdd Binary.cpp
63 lines (63 loc) · 1.45 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
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution {
public:
string addBinary(string a, string b) {
if(a.length() < b.length())
return addBinary(b, a);
bool carry = false;
int i = 0, m = a.size(), n = b.size();
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
string ans;
while(i < n)
{
if(a[i] == '0' && b[i] == '0')
{
if(carry)
{
ans += "1";
carry = false;
}
else
ans += "0";
}
else if(a[i] == '1' && b[i] == '1')
{
if(carry)
ans += "1";
else
{
ans += "0";
carry = true;
}
}
else
{
if(carry)
ans += "0";
else
ans += "1";
}
i++;
}
while(i < m)
{
if(carry)
{
if(a[i] == '0')
{
ans += "1";
carry = false;
}
else
ans += "0";
}
else
ans += a[i];
i++;
}
if(carry)
ans += "1";
reverse(ans.begin(), ans.end());
return ans;
}
};