Skip to content

Commit 3456800

Browse files
committed
二进制加法
1 parent 5faf67a commit 3456800

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

lcof2/剑指 Offer II 002. 二进制加法/Solution.cpp

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,53 @@ class Solution {
1111
reverse(ans.begin(), ans.end());
1212
return ans;
1313
}
14-
};
14+
};
15+
16+
#include <iostream>
17+
#include <algorithm>
18+
19+
using namespace std;
20+
21+
class Solution {
22+
public:
23+
string addBinary(string a, string b) {
24+
string ans;
25+
int i = a.size() - 1;
26+
int j = b.size() - 1;
27+
for(int carry = 0; i >= 0 || j >= 0 || carry; i--, j--)
28+
{
29+
carry += (i > -1 ? (a[i] - '0') : 0) + (j > -1 ? ( b[j] - '0') : 0);
30+
switch(carry)
31+
{
32+
case 0:
33+
ans.push_back('0');
34+
break;
35+
case 1:
36+
ans.push_back('1');
37+
carry = 0;
38+
break;
39+
case 2:
40+
ans.push_back('0');
41+
carry = 1;
42+
break;
43+
case 3:
44+
ans.push_back('1');
45+
carry = 1;
46+
break;
47+
}
48+
}
49+
reverse(ans.begin(), ans.end());
50+
return ans;
51+
}
52+
};
53+
54+
int main()
55+
{
56+
Solution solution;
57+
58+
string a = "11";
59+
string b = "10";
60+
string result = solution.addBinary(a, b);
61+
cout << "The sum of " << a << " and " << b << " is: " << result << endl;
62+
return 0;
63+
}

0 commit comments

Comments
 (0)