Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2418 from atulpatildbz/0067_add_binary-c
Browse files Browse the repository at this point in the history
Create 0067-add-binary.c
  • Loading branch information
MHamiid authored Apr 16, 2023
2 parents b3d1baa + e75b429 commit 6029314
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions c/0067-add-binary.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
char *addBinary(const char *a, const char *b) {
int maxLen = strlen(a) > strlen(b) ? strlen(a) : strlen(b);
char *res = (char *)malloc((maxLen + 2) * sizeof(char));
memset(res, 0, (maxLen + 2) * sizeof(char));
unsigned int carry = 0;

for(int i = 0; i < maxLen; i++) {
unsigned int bitA = i < strlen(a) ? a[strlen(a) - i - 1] - '0' : 0;
unsigned int bitB = i < strlen(b) ? b[strlen(b) - i - 1] - '0' : 0;

unsigned int total = bitA + bitB + carry;
char sum = '0' + total % 2;
carry = total / 2;

// Add to the beginning of the string
memmove(res + 1, res, strlen(res));
res[0] = sum;
}
if(carry) {
memmove(res + 1, res, strlen(res));
res[0] = '1';
}
return res;
}

0 comments on commit 6029314

Please sign in to comment.