-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_binary.c
More file actions
61 lines (46 loc) · 1.49 KB
/
Copy pathadd_binary.c
File metadata and controls
61 lines (46 loc) · 1.49 KB
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
58
59
60
61
char * addBinary(char * a, char * b){
int a_index = strlen(a) - 1;
int b_index = strlen(b) - 1;
int write_index = 0;
char* result_string = calloc((a_index + b_index + 3), sizeof(char));
int carry_digit = 0;
while(a_index >= 0 &&
b_index >= 0)
{
int a_digit = a[a_index] == '1';
int b_digit = b[b_index] == '1';
int result = a_digit + b_digit + carry_digit;
carry_digit = result > 1;
result = result % 2;
result_string[write_index++] = (result == 0) ? '0' : '1';
a_index--;
b_index--;
}
while(a_index >= 0) {
int a_digit = a[a_index] == '1';
int result = a_digit + carry_digit;
carry_digit = result > 1;
result = result % 2;
result_string[write_index++] = (result == 0) ? '0' : '1';
a_index--;
}
while(b_index >= 0) {
int b_digit = b[b_index] == '1';
int result = b_digit + carry_digit;
carry_digit = result > 1;
result = result % 2;
result_string[write_index++] = (result == 0) ? '0' : '1';
b_index--;
}
if(carry_digit) {
result_string[write_index++] = '1';
}
int front = 0;
int back = write_index - 1;
while(front < back) {
char temp = result_string[front];
result_string[front++] = result_string[back];
result_string[back--] = temp;
}
return result_string;
}