Skip to content

Commit 3ea2d3c

Browse files
committed
jianzhi offer 2
1 parent ce3db28 commit 3ea2d3c

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

JianZhiOffer/2.cpp

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <iostream>
2+
#include <algorithm>
3+
#include <string>
4+
5+
using namespace std;
6+
7+
class Solution {
8+
public:
9+
string addBinary(string a, string b) {
10+
int la = a.size() - 1;
11+
int lb = b.size() - 1;
12+
int carry = 0;
13+
string results;
14+
while(la >= 0 || lb >= 0)
15+
{
16+
int aa = la >= 0 ? a[la] - '0' : 0;
17+
int bb = lb >= 0 ? b[lb] - '0' : 0;
18+
int sum = aa + bb + carry;
19+
carry = sum >= 2 ? 1: 0;
20+
sum = sum >= 2 ? sum - 2: sum;
21+
22+
results.push_back('0' + sum);
23+
la -= 1;
24+
lb -= 1;
25+
}
26+
if (carry == 1)
27+
results.push_back('1');
28+
reverse(results.begin(), results.end());
29+
return results;
30+
}
31+
};
32+
33+
int main(void)
34+
{
35+
Solution sol = Solution();
36+
string results = sol.addBinary("101111", "10");
37+
cout << results << endl;
38+
}

0 commit comments

Comments
 (0)