forked from Thelalitagarwal/GFG_Daily_Problem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd Binary Strings.cpp
More file actions
52 lines (47 loc) · 1.09 KB
/
Add Binary Strings.cpp
File metadata and controls
52 lines (47 loc) · 1.09 KB
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
class Solution{
public:
string addBinary(string A, string B)
{
string ans = "";
int i = A.size() - 1, j = B.size() - 1;
bool carry = 0;
while(i >= 0 || j >= 0)
{
int sum = 0;
if(i >= 0 && A[i] == '1')
sum++;
if(j >= 0 && B[j] == '1')
sum++;
if(sum + carry == 3)
{
ans += '1';
carry = 1;
}
else if(sum + carry == 2)
{
ans += '0';
carry = 1;
}
else if(sum + carry == 1)
{
ans += '1';
carry = 0;
}
else
{
ans += '0';
carry = 0;
}
i--; j--;
}
if(carry == 1)
ans += to_string(carry);
reverse(ans.begin(), ans.end());
i = 0;
while(ans[i] == '0')
{
ans.erase(0, 1);
}
return ans;
}
};