-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0067_add_binary.c
57 lines (52 loc) · 1.48 KB
/
0067_add_binary.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* Author: Xiangyue Cai
* Date: 2019-09-25
*/
// Example 1:
// Input: a = "11", b = "1"
// Output: "100"
// Example 2:
// Input: a = "1010", b = "1011"
// Output: "10101"
// runtime: 0ms beats 100%
// memory usage: 7mb beats 75%
char*
addBinary(char * a, char * b){
int a_len = strlen(a) - 1;
int b_len = strlen(b) - 1;
int r_len = (a_len > b_len? a_len : b_len) + 3;
char *res = malloc(r_len);
res[--r_len] = '\0';
int carry = 0;
while (a_len > -1 || b_len > -1) {
char ch_a = a_len > -1 ? a[a_len--] : '0';
char ch_b = b_len > -1 ? b[b_len--] : '0';
if (ch_a == '1' && ch_b == '1' && carry == 0) {
carry = 1;
res[--r_len] = '0';
}
else if (((ch_a == '1' && ch_b == '0') || (ch_a == '0' && ch_b == '1')) && carry == 0 ) {
carry = 0;
res[--r_len] = '1';
}
else if (ch_a == '0' && ch_b == '0' && carry == 0) {
carry = 0;
res[--r_len] = '0';
}
else if (ch_a == '1' && ch_b == '1' && carry == 1) {
carry = 1;
res[--r_len] = '1';
}
else if (((ch_a == '1' && ch_b == '0') || (ch_a == '0' && ch_b == '1')) && carry == 1 ) {
carry = 1;
res[--r_len] = '0';
}
else if (ch_a == '0' && ch_b == '0' && carry == 1) {
carry = 0;
res[--r_len] = '1';
}
}
if (carry) res[--r_len] = '1';
else return res+1;
return res;
}