21 lines C Accepted 6ms


  • 0
    J

    char* addStrings(char* num1, char* num2) {
    char tmp[5102] = {0};
    int l1 = strlen(num1);
    int l2 = strlen(num2);
    int sum = 0, carry = 0, index = 5101;
    char *res = NULL;
    while(l1||l2){
    if(l1)sum = num1[l1---1] - '0';
    if(l2)sum += num2[l2---1] - '0';
    sum += carry;
    carry = sum >= 10 ? sum/10 : 0;
    tmp[index--] = (sum >= 10 ? sum%10 : sum) + '0';
    sum = 0;
    }
    if(carry){
    tmp[index--] = carry + '0';
    }
    res = malloc(5102);
    strcpy(res, &tmp[index+1]);
    return res;
    }


Log in to reply
 

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