-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd binary
More file actions
37 lines (32 loc) · 885 Bytes
/
Add binary
File metadata and controls
37 lines (32 loc) · 885 Bytes
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
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
---------------------------------------------------------------------------------------------------------------
// n=a.length(), m=b.length() tc=O(n+m) sc=O(n+m)
class Solution {
public:
string addBinary(string a, string b) {
string res="";
int i=a.size()-1, j=b.size()-1;
int carry=0;
while(i>=0 || j>=0 || carry){
int sum=carry;
if(i>=0){
sum+=a[i]-'0';
i--;
}
if(j>=0){
sum+=b[j]-'0';
j--;
}
res+=(sum%2)+'0';
carry=sum/2;
}
reverse(res.begin(), res.end());
return res;
}
};