forked from sunstick/code-street
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_binary.cpp
More file actions
36 lines (29 loc) · 734 Bytes
/
add_binary.cpp
File metadata and controls
36 lines (29 loc) · 734 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
/*
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
*/
class Solution {
public:
string addBinary(string a, string b) {
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
string res = "";
int carry = 0;
int n = max(a.size(), b.size());
int i = 0;
while (i < n || carry) {
int ai = i < a.size() ? a[i] - '0' : 0;
int bi = i < b.size() ? b[i] - '0' : 0;
int bit = ai + bi + carry;
carry = bit / 2;
bit = bit % 2;
res += (bit + '0');
i++;
}
reverse(res.begin(), res.end());
return res;
}
};