Share My C++ Code Easy To Understand


  • 0
    R

    Basic idea is to store each number in a vector, compute the sum, and create a listnode to store the result.

    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            vector<int> num1;
            vector<int> num2;
            
            ListNode *head = l1;
            while (head != NULL) {
                num1.push_back(head->val);
                head = head -> next;
            }
            
            head = l2;
            while (head != NULL) {
                num2.push_back(head->val);
                head = head -> next;
            }
            
            vector<int> res;
            
            int n1 = num1.size() - 1;
            int n2 = num2.size() - 1;
    
            int carry = 0;
            int sum = 0;
           
            while (n1 >= 0 && n2 >= 0) {
    
                sum = num1[n1] + num2[n2] + carry;
                carry = sum / 10;
                res.push_back(sum % 10);
                n1--;
                n2--;
            }
    
            if (n1 == -1) {
                if (n2 == -1) {
                    if (carry != 0) {
                        res.push_back(carry);
                        carry = 0;
                    }
                }
                else {
                    while (n2 >= 0) {
                        sum = num2[n2] + carry;
                        carry = sum / 10;
                        res.push_back(sum % 10);
                        n2--;
                    }
                }
            }
            else {
                while (n1 >= 0) {
                    sum = num1[n1] + carry;
                    carry = sum / 10;
                    res.push_back(sum % 10);
                    n1--;
                }
            }
            if (carry != 0) {
                res.push_back(carry);
            }
            ListNode sentinel(0);
            head = &sentinel;
            
            for (int i = res.size() - 1; i >= 0; i--) {
                ListNode *curr = new ListNode(res[i]);
                head->next = curr;
                head = curr;
            }
            return sentinel.next;
        }
    };
    

Log in to reply
 

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