File tree Expand file tree Collapse file tree 1 file changed +50
-1
lines changed
lcof2/剑指 Offer II 002. 二进制加法 Expand file tree Collapse file tree 1 file changed +50
-1
lines changed Original file line number Diff line number Diff line change @@ -11,4 +11,53 @@ class Solution {
11
11
reverse (ans.begin (), ans.end ());
12
12
return ans;
13
13
}
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
+ }
You can’t perform that action at this time.
0 commit comments