-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathAdd Binary.cpp
50 lines (39 loc) · 1.3 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
/*
Solution by Rahul Surana
***********************************************************
Given two binary strings a and b, return their sum as a binary string.
***********************************************************
*/
#include <bits/stdc++.h>
class Solution {
public:
string addBinary(string a, string b) {
int n = a.length()-1,m = b.length()-1;
string ans(max(n,m)+2,'a');
int k = max(n,m)+1;
int c = 0;
int i;
while(0 <= n && 0 <= m){
if(a[n]=='1' && b[m] == '1'){
ans[k] = c + '0';
c=1;
} else if(a[n]=='1' || b[m] == '1'){
ans[k] = (c^1) + '0';
// c=c^1;
}
else{
ans[k] = c + '0';
c = 0;
}
// cout << n<<" "<<m<<" "<<ans<<"\n";
n--;
m--;
k--;
}
while(n>=0){ if(a[n] == '1') ans[k--] = (c^1)+'0'; else { ans[k--] = c+'0'; c = 0; } n--; }
while(m>=0){ if(b[m] == '1') ans[k--] = (c^1)+'0'; else { ans[k--] = c+'0'; c = 0; } m--; }
// cout << n<<" "<<m<<" "<<c<<" "<<ans<<"\n";
if(c) { ans[k] = '1'; return ans;}
return ans.substr(1);
}
};