Easy and fast C 3ms solution


  • 1
    #define pointAt(a,b,c) (a+b-1-c)
    #define getDigAt(a,b,c) (((c)<(b))?(*((a)+(b)-1-(c))-'0'):0)
    char* addStrings(char* num1, char* num2) {
        int len1 = strlen(num1);
        int len2 = strlen(num2);
        char* res = malloc(5101*sizeof(char));
        *(res+5100) = 0;
        int i=0;
        int adding = 0;
        int tmp;
        while(i<len1 || i<len2){
            tmp = getDigAt(num1, len1, i) + getDigAt(num2, len2, i) + adding;
            adding = tmp/10;
            *pointAt(res, 5100, i) = tmp%10 + '0';
            i++;
        }
        if(adding!=0){
            *pointAt(res, 5100, i)=adding + '0';
            return pointAt(res, 5100, i);
        }else{
            return pointAt(res, 5100, i+1);
        }
    }
    

  • 2
    S

    This might cause heap corruption if you allocate memory region X and pass back a pointer which is within X.
    Who is going to free X?


Log in to reply
 

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