Skip to content

Commit 9c38ca4

Browse files
committed
Update add-binary.cpp
1 parent f2ad6af commit 9c38ca4

1 file changed

Lines changed: 41 additions & 11 deletions

File tree

C++/add-binary.cpp

Lines changed: 41 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,53 @@
44
class Solution {
55
public:
66
string addBinary(string a, string b) {
7-
string result;
8-
int result_length = max(a.length(), b.length()) ;
7+
string res;
8+
size_t res_len = max(a.length(), b.length()) ;
99

10-
int carry = 0;
11-
for (int i = 0; i < result_length; ++i) {
12-
int a_bit_i = i < a.length() ? a[a.length() - 1 - i] - '0' : 0;
13-
int b_bit_i = i < b.length() ? b[b.length() - 1 - i] - '0' : 0;
14-
int sum = carry + a_bit_i + b_bit_i;
10+
size_t carry = 0;
11+
for (int i = 0; i < res_len; ++i) {
12+
const size_t a_bit_i = i < a.length() ? a[a.length() - 1 - i] - '0' : 0;
13+
const size_t b_bit_i = i < b.length() ? b[b.length() - 1 - i] - '0' : 0;
14+
size_t sum = carry + a_bit_i + b_bit_i;
1515
carry = sum / 2;
1616
sum %= 2;
17-
result.push_back('0' + sum);
17+
res.push_back('0' + sum);
1818
}
1919
if (carry) {
20-
result.push_back('0' + carry);
20+
res.push_back('0' + carry);
2121
}
22-
reverse(result.begin(), result.end());
22+
reverse(res.begin(), res.end());
2323

24-
return result;
24+
return res;
25+
}
26+
};
27+
28+
class Solution2 {
29+
public:
30+
string addBinary(string a, string b) {
31+
size_t carry = 0;
32+
string res;
33+
34+
for (auto a_it = a.rbegin(), b_it = b.rbegin(); a_it != a.rend() || b_it != b.rend();) {
35+
const size_t a_bit_i = (a_it != a.rend()) ? *a_it - '0' : 0;
36+
const size_t b_bit_i = (b_it != b.rend()) ? *b_it - '0' : 0;
37+
size_t sum = a_bit_i + b_bit_i + carry;
38+
carry = sum / 2;
39+
sum %= 2;
40+
res.push_back('0' + sum);
41+
42+
if (a_it != a.rend()) {
43+
++a_it;
44+
}
45+
if (b_it != b.rend()) {
46+
++b_it;
47+
}
48+
}
49+
if (carry) {
50+
res.push_back('0' + carry);
51+
}
52+
reverse(res.begin(), res.end());
53+
54+
return res;
2555
}
2656
};

0 commit comments

Comments
 (0)