C solution (0ms) - using `realloc` to grow the return string


  • 0
    #define swap(x, y)   { int z = x; x = y; y = z; }
    
    char* addBinary(char* num1, char* num2) {
        int i = strlen(num1), j = strlen(num2), sum = 0;
        char *result = NULL, resultSize = 0;
        while (i || j || sum) {
            if (i) sum += num1[i-- - 1] - '0';
            if (j) sum += num2[j-- - 1] - '0';
            result = realloc(result, ++resultSize * sizeof(char));
            result[resultSize - 1] = (sum % 2) + '0';
            sum /= 2;
        }
        // Reverse the result
        for (i = 0, j = resultSize - 1; i < j; i++, j--) swap(result[i], result[j]);
        result = realloc(result, ++resultSize * sizeof(char));
        // Null terminaton for the result string
        result[resultSize - 1] = 0;
        return result;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.