forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
add-binary.cpp
57 lines (50 loc) · 1.5 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
51
52
53
54
55
56
57
// Time: O(n)
// Space: O(1)
class Solution {
public:
string addBinary(string a, string b) {
string res;
size_t res_len = max(a.length(), b.length()) ;
size_t carry = 0;
for (int i = 0; i < res_len; ++i) {
const size_t a_bit_i = i < a.length() ? a[a.length() - 1 - i] - '0' : 0;
const size_t b_bit_i = i < b.length() ? b[b.length() - 1 - i] - '0' : 0;
size_t sum = carry + a_bit_i + b_bit_i;
carry = sum / 2;
sum %= 2;
res.push_back('0' + sum);
}
if (carry) {
res.push_back('0' + carry);
}
reverse(res.begin(), res.end());
return res;
}
};
// Iterator solution.
class Solution2 {
public:
string addBinary(string a, string b) {
size_t carry = 0;
string res;
for (auto a_it = a.rbegin(), b_it = b.rbegin(); a_it != a.rend() || b_it != b.rend();) {
const size_t a_bit_i = (a_it != a.rend()) ? *a_it - '0' : 0;
const size_t b_bit_i = (b_it != b.rend()) ? *b_it - '0' : 0;
size_t sum = a_bit_i + b_bit_i + carry;
carry = sum / 2;
sum %= 2;
res.push_back('0' + sum);
if (a_it != a.rend()) {
++a_it;
}
if (b_it != b.rend()) {
++b_it;
}
}
if (carry) {
res.push_back('0' + carry);
}
reverse(res.begin(), res.end());
return res;
}
};