My 20ms solution in C,how can it be 16ms?


  • 0
    H
        int cal(int a, int b, int *carry)
     {
         int sum = a+b+*carry;
         *carry = sum/10;
         return sum%10;
     }
     
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        int carry = 0;
        struct ListNode* head = l1;
        struct ListNode* pre = l1;
        if (l1 == NULL){
            return l2;
        }
        else if (l2 == NULL){
            return l1;
        }
        l1->val = cal(l1->val,l2->val,&carry);
        l1 = l1->next;
        l2 = l2->next;
        while (l1 && l2){ 
                pre->next->val = cal(l1->val,l2->val,&carry);
                pre = pre->next;
                l1 = l1->next;
                l2 = l2->next;
        }
        if (l2){ //if l2 is longer.
            pre->next = l2;
        }
        while (carry){
            if (pre->next){
                pre->next->val = cal(pre->next->val,0,&carry);
                pre = pre->next;
            }
            else{
                pre->next = malloc(sizeof(struct ListNode));
                pre->next->val = cal(0,0,&carry);
                pre->next->next = NULL;
            }
         }
        return head;
    }

  • 2
    N

    From my observation, the slice difference between 16ms and 20ms due to the network condition during your submition, rather than your code speed. That time is just a reference, not accuracy time your program spend. Trust me, I have tried submit the same code for several times. Sometimes I got 16ms, some times I got 20ms.


  • 0
    H

    Thank you for your answer, I thank you are right.I am done with it.


Log in to reply
 

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