LC 2. Add Two Numbers

Nilanjan Deb · April 5, 2020

This is my CPP solution.

class Solution {
private:
    int lenCount(ListNode* head){
        int n = 0;
        ListNode* temp = head;
        while(temp){
            n++;
            temp = temp->next;
        }
        return n;
    }
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int n1 = lenCount(l1), n2 = lenCount(l2);
        if(n1<n2){
            ListNode* temp = l1;
            l1 = l2;
            l2 = temp;
        }
        ListNode *res = l1;
        int carry = 0;
        while(l2!=NULL){
            int sum = l2->val + l1->val + carry;
            l1->val = sum%10;
            carry = sum/10;
            l2 = l2->next;
            if(l1->next==NULL && carry){
                ListNode* newNode = new ListNode();
                newNode->val = carry;
                newNode->next = NULL;
                l1->next = newNode;
                return res;
            }
            l1 = l1->next;
        }
        while(l1!=NULL){
            int sum = l1->val + carry;
            l1->val = sum%10;
            carry = sum/10;
            if(l1->next==NULL && carry){
                ListNode* newNode = new ListNode;
                newNode->val = carry;
                newNode->next = NULL;
                l1->next = newNode;
                return res;
            }
            l1 = l1->next;
        }
        return res;
    }
};


Dicussion Forum