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
+ class Solution {
2
+ public:
3
+ string addBinary (string a, string b) {
4
+ // Start typing your C/C++ solution below
5
+ // DO NOT write int main() function
6
+
7
+ string c;
8
+ int len_a = a.size ();
9
+ int len_b = b.size ();
10
+ int carry = 0 ;
11
+ for (int i = 0 ; i < min (len_a, len_b); i++) {
12
+ int x = a[len_a - i - 1 ] - ' 0' ;
13
+ int y = b[len_b - i - 1 ] - ' 0' ;
14
+ c += (x + y + carry) % 2 + ' 0' ;
15
+ carry = (x + y + carry) / 2 ;
16
+ }
17
+ if (len_a > len_b) {
18
+ for (int i = len_b; i < len_a; i++) {
19
+ int x = a[len_a - i - 1 ] - ' 0' ;
20
+ c += (x + carry) % 2 + ' 0' ;
21
+ carry = (x + carry) / 2 ;
22
+ }
23
+ }
24
+ else if (len_a < len_b) {
25
+ for (int i = len_a; i < len_b; i++) {
26
+ int x = b[len_b - i - 1 ] - ' 0' ;
27
+ c += (x + carry) % 2 + ' 0' ;
28
+ carry = (x + carry) / 2 ;
29
+ }
30
+ }
31
+ while (carry) {
32
+ c += carry % 2 + ' 0' ;
33
+ carry /= 2 ;
34
+ }
35
+ reverse (c.begin (), c.end ());
36
+ return c;
37
+ }
38
+ };
You can’t perform that action at this time.
0 commit comments