-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path67.add-binary.c
More file actions
48 lines (37 loc) · 1.03 KB
/
67.add-binary.c
File metadata and controls
48 lines (37 loc) · 1.03 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
/*
* @lc app=leetcode id=67 lang=c
*
* [67] Add Binary
*/
// @lc code=start
char *addBinary(char *a, char *b)
{
int lenA = strlen(a);
int lenB = strlen(b);
int max_size = lenA > lenB ? lenA : lenB;
char *result = (char *)malloc((max_size + 2) * sizeof(char)); // +2 for potential carry and null terminator
result[max_size + 1] = '\0'; // Null-terminate the result string
int carry = 0;
int indexA = lenA - 1;
67.add - binary.c int indexB = lenB - 1;
int resultIndex = max_size;
while (indexA >= 0 || indexB >= 0 || carry)
{
int sum = carry;
if (indexA >= 0)
{
sum += a[indexA] - '0';
indexA--;
}
if (indexB >= 0)
{
sum += b[indexB] - '0';
indexB--;
}
carry = sum / 2;
result[resultIndex] = (sum % 2) + '0';
resultIndex--;
}
return result + resultIndex + 1; // Return the address of the start of the result string
}
// @lc code=end