My 16ms C solution in 16 lines


  • 0
    M
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode *newList() { // construct and initialize a list
            struct ListNode *list = malloc(sizeof(struct ListNode));
            list->val = list->next = 0;
            return list;}
        int add1 = 0;
        struct ListNode *ret = newList();
        struct ListNode *current = ret;
        while(l1 || l2 || add1) {
            struct ListNode *l = newList();
            if(l1) {l->val += l1->val; l1 = l1->next;}
            if(l2) {l->val += l2->val; l2 = l2->next;}
            l->val += add1 ? (add1--) : 0; // set add1 to 0
            l->val -= (l->val >= 10) ? (10+add1++) : 0; // set add1 to 1 if l->val >= 10
            current = current->next = l;}
        return ret->next;}

  • 0
    C

    this is not 16 lines.
    you fold too much


Log in to reply
 

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