File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments