-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add Binary Strings.cpp
61 lines (61 loc) · 1.36 KB
/
Add Binary Strings.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
class Solution {
public:
string addBinary(string& s1, string& s2) {
reverse(s1.begin(), s1.end());
reverse(s2.begin(), s2.end());
string ans = "";
char curr;
int carry = 0, i = 0;
while(carry > 0 || i < s1.length() || i < s2.length())
{
int sum = carry;
if(i < s1.length())
{
if(s1[i] == '1')
{
sum++;
}
}
if(i < s2.length())
{
if(s2[i] == '1')
{
sum++;
}
}
if(sum == 0)
{
carry = 0;
curr = '0';
}
else if(sum == 1)
{
carry = 0;
curr = '1';
}
else if(sum == 2)
{
carry = 1;
curr = '0';
}
else
{
carry = 1;
curr = '1';
}
ans.push_back(curr);
i++;
}
reverse(ans.begin(), ans.end());
int ind = 0;
while(ind < ans.length())
{
if(ans[ind] == '1')
{
break;
}
ind++;
}
return ans.substr(ind);
}
};