Simple but verbose 32ms C++ solution


  • 0
    E
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int carry = 0;
        ListNode *result = l1, *prev = l1;
        
        
        while (l1 != NULL || l2 != NULL)
        {
            
            if (l1 != NULL && l2 != NULL )
            {
                int value = l1->val + l2->val + carry;
                l1->val = value % 10;
                carry = (value) / 10;
                prev = l1;
                l1 = l1->next;
                l2 = l2->next;
            }
            else if ( l1 !=NULL)
            {
                int value = (l1->val + carry);
                l1->val = (value) % 10;
                carry = (value) / 10;
                prev = l1;
                l1 = l1->next;
    
            }
            else if (l2 != NULL)
            {
                ListNode *node = new ListNode((l2->val + carry)%10);
                node->next = NULL;
                prev->next = node;
                carry = (l2->val + carry) / 10;
                prev = node;
                //l1 = prev->next->next;
                l2 = l2->next;
            }
        }
        
        if (carry == 1)
        {
            prev->next = new ListNode(1);
            prev->next->next = NULL;
        }
        return result;
        
    }
    

    };


Log in to reply
 

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