-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathadd_binary.cpp
More file actions
43 lines (43 loc) · 1.08 KB
/
Copy pathadd_binary.cpp
File metadata and controls
43 lines (43 loc) · 1.08 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
class Solution {
/*
@Author - Jatin Goel
@Institute - IIIT Allahabad
Hardwork definitely pays off.
There is no substitute of hardwork.
There is no shortcut to success.
*/
public:
string addBinary(string a, string b) {
string ans = "";
int carry = 0;
int i=a.size()-1;
int j=b.size()-1;
while(i>=0 && j>=0)
{
int x = a[i--]-'0' , y = b[j--]-'0';
int sum = x^y^carry;
carry = x&y | y&carry | x&carry;
char c = sum + '0';
ans = c + ans;
}
while(i>=0)
{
int x = a[i--]-'0' , y = 0;
int sum = x^y^carry;
carry = x&y | y&carry | x&carry;
char c = sum + '0';
ans = c + ans;
}
while(j>=0)
{
int x = 0 , y = b[j--] - '0';
int sum = x^y^carry;
carry = x&y | y&carry | x&carry;
char c = sum + '0';
ans = c + ans;
}
cout << carry << endl;
ans = (carry?"1":"") + ans;
return ans;
}
};