C, 3ms


  • 0
    Y
    #define BUF_LEN 5100
    
    char* addStrings(char* num1, char* num2) {
        size_t ns1 = num1 == NULL ? 0 : strlen(num1);
        size_t ns2 = num2 == NULL ? 0 : strlen(num2);
        
        if (ns1 < ns2) {
            return addStrings(num2, num1);
        }
        
        if (ns2 == 0) {
            return num1 == NULL ? NULL : strdup(num1);
        } 
        
        char *buf = (char *) malloc(BUF_LEN);
    
        char *p1 = num1 + ns1 - 1;
        char *p2 = num2 + ns2 - 1;
        int carry = 0;
        int val = 0;
        char *pb = buf;
        while (p2 >= num2) {
            val = *(p1--) + *(p2--) - 2 * '0' + carry;
            if (val >= 10) {
                carry = 1;
                val -= 10;
            } else {
                carry = 0;
            }
            *(pb++) = '0' + val;
        }
    
        while (p1 >= num1 && carry != 0) {
            val = *(p1--) - '0' + carry;
            if (val >= 10) {
                carry = 1;
                val -= 10;
            } else {
                carry = 0;
            }
            *(pb++) = '0' + val;
        }
            
        while (p1 >= num1) {
            *(pb++) = *(p1--);
        }
        
        if (carry != 0) {
            *(pb++) = '1';
        }
    
        *pb = '\0';
        for (char *b = buf, *e = pb - 1; b < e; ++b, --e) {
            *b ^= *e;
            *e ^= *b;
            *b ^= *e;
        }
        
        return buf;
    }
    

Log in to reply
 

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