Skip to content

Commit 6029314

Browse files
authored
Merge pull request #2418 from atulpatildbz/0067_add_binary-c
Create 0067-add-binary.c
2 parents b3d1baa + e75b429 commit 6029314

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

c/0067-add-binary.c

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
char *addBinary(const char *a, const char *b) {
2+
int maxLen = strlen(a) > strlen(b) ? strlen(a) : strlen(b);
3+
char *res = (char *)malloc((maxLen + 2) * sizeof(char));
4+
memset(res, 0, (maxLen + 2) * sizeof(char));
5+
unsigned int carry = 0;
6+
7+
for(int i = 0; i < maxLen; i++) {
8+
unsigned int bitA = i < strlen(a) ? a[strlen(a) - i - 1] - '0' : 0;
9+
unsigned int bitB = i < strlen(b) ? b[strlen(b) - i - 1] - '0' : 0;
10+
11+
unsigned int total = bitA + bitB + carry;
12+
char sum = '0' + total % 2;
13+
carry = total / 2;
14+
15+
// Add to the beginning of the string
16+
memmove(res + 1, res, strlen(res));
17+
res[0] = sum;
18+
}
19+
if(carry) {
20+
memmove(res + 1, res, strlen(res));
21+
res[0] = '1';
22+
}
23+
return res;
24+
}

0 commit comments

Comments
 (0)