PU Add Binary

Jan 01, 1970

Given two binary strings, return their sum (also a binary string).

Example:

  • a = "11" b = "1"
  • Return "100".

C Solution:

char* addBinary(char* a, char* b) {
    int lena = strlen(a), lenb = strlen(b);
    int len = (lena > lenb ? lena : lenb) + 2;
    char *res = malloc(len);
    res[len - 1] = 0;
    int k = len - 2, carry = 0, i, j;
    for (i = lena - 1, j = lenb - 1; i > -1 || j > -1 || carry; i--, j--, k--) {
        if (i > -1) carry += a[i] - '0';
        if (j > -1) carry += b[j] - '0';
        res[k] = (carry & 1) + '0';
        carry >>= 1;
    }
    if (k != -1) {
        for (i = 1; i < len; i++) res[i - 1] = res[i];
    }
    return res;
}

Summary:

  1. Don't return res + 1, that's pretty evil.
  2. The efficiency can be improved, but the code will be more complex.
  3. 3ms, 5.68%

LeetCode: 67. Add Binary