My 3 ms C solution


  • 0

    Given there might be a carry at the top digit, we need one more element.

    char* addStrings(char* num1, char* num2) {
        int len1 = strlen(num1);
        int len2 = strlen(num2);
        int maxlen = len1 > len2 ? len1 : len2;
        char* res = (char*)malloc((maxlen+2)*sizeof(char));
        res[maxlen+1] = '\0';
        int carry = 0;
        --len1; --len2;
        while(len1 >= 0 || len2 >= 0) {
            int temp;
            if(len1 >= 0 && len2 >= 0)
                temp = num1[len1--] - '0' + num2[len2--] - '0' + carry;
            else if(len1 >= 0 && len2 < 0)
                temp = num1[len1--] - '0' + carry;
            else
                temp = num2[len2--] - '0' + carry;
            res[maxlen--] = temp % 10 + '0';
            carry = temp / 10;
        }
        if(carry) {
            res[0] = '1';
            return res;
        }
        return res + 1;
    }
    

Log in to reply
 

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