Leet Code : Add Two List – Java | CPP | Javascript | Python

You are given two non-empty linked lists that each represent a non-negative integer. The digits are kept in reverse order, with each node containing only one digit. Add the two numbers together and return the total as a linked list.

Except for the number 0 itself, you may presume that the two numbers do not have any leading zeros.

Eg 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]

Explanation: 342 + 465 = 807.

Example 2:

Input: l1 = [0], l2 = [0]
Output: [0]

Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

Solution:

CPP :

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* head=NULL;
        int carry=0;
        while(l1!=NULL || l2!=NULL || carry!=0)
        {
            int sum=0;
            if(l1!=NULL)
            {
                sum+=l1->val;
                l1=l1->next;
            }
            if(l2!=NULL)
            {
                sum+=l2->val;
                l2=l2->next;
            }
            sum+=carry;
            carry=sum/10;
            ListNode* node=new ListNode(sum%10);
            // to add the first node in the newly created list (head node)
            if(head==NULL)
            {
                head=node;
                continue;  //forwards the loop for further itreation before moving further
            }
            
            // to add the remaining list except the head node
            ListNode* temp=head;
            while(temp->next!=NULL)
            {
                temp=temp->next;
            }
            temp->next=node;
        }
        return head;
    }
};

Java

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int count = 1;
        int carry = 0;
        ListNode resultNode = new ListNode();
        ListNode nextNode = resultNode;
        while(l1 != null || l2 != null || carry != 0) {
            int sum = carry;
            if(l1 != null){
               sum += l1.val;
                l1 = l1.next;
            } 
                
            if(l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            } 
            
            if(sum >9) {
                carry = 1;
                nextNode.val = sum - 10;
            } else {
                carry = 0;
                nextNode.val = sum;
            }
            if(l1 != null || l2 != null || carry != 0) {
                nextNode.next = new ListNode();
                nextNode = nextNode.next;
            }
        }
        return resultNode;
    }
}

Python :

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        head=ListNode()
        
        tail=ListNode()
        
        a=list()
        b=list()
        while(l1!=None):
            a.append(l1.val)
            l1=l1.next
        while(l2!=None):
            b.append(l2.val)
            l2=l2.next
        a.reverse()
        b.reverse()
        print(a)
        print(b)
        res=list()
        carry=0
        if(len(a)>=len(b)):
            i=len(a)-1
            j=len(b)-1
            while(i>=0):
                if j >=0:
                    s=a[i]+b[j]+carry
                else:
                    s=a[i]+carry
                if (s<10):
                    res.append(s)
                    carry=0
                else:
                    res.append(s%10)
                    s=s//10
                    carry=s
                i-=1  
                j-=1
            if carry!=0:
                res.append(carry)
            print(res)
            
            for i in range (0,len(res)):
                temp=ListNode()
               
                temp.val=res[i]
                # print(temp.val)
                temp.next=None
                
                if i==0:
                    head=temp
                    tail=temp
                else:
                    tail.next=temp
                    tail=temp
                print(tail.val)
            # print(head)
            
        elif(len(b)>=len(a)):
            res=list()
            carry=0
            i=len(b)-1
            j=len(a)-1
            while(i>=0):
                if j >=0:
                    s=a[j]+b[i]+carry
                else:
                    s=b[i]+carry
                if (s<10):
                    res.append(s)
                    carry=0
                else:
                    res.append(s%10)
                    s=s//10
                    carry=s
                i-=1  
                j-=1
            if carry!=0:
                res.append(carry)
            print(res)
            
            for i in range (0,len(res)):
                temp=ListNode()
               
                temp.val=res[i]
                # print(temp.val)
                temp.next=None
                
                if i==0:
                    head=temp
                    tail=temp
                else:
                    tail.next=temp
                    tail=temp
                print(tail.val)
        return head

Java Script:

var addTwoNumbers = function(l1, l2) {
    const zeroNode = new ListNode();
    let l3 = zeroNode;
    let carry = 0;
    
    while (l1 || l2) {
        const value1 = l1?.val || 0;
        const value2 = l2?.val || 0;
        const sum = value1 + value2 + carry;
        const value3 = sum % 10;
        
        carry = Math.floor(sum / 10);
        
        l1 = l1 ? l1.next : null;
        l2 = l2 ? l2.next : null;
        l3.next = new ListNode(value3);
        l3 = l3.next;
    }
    
    if (carry) {
        l3.next = new ListNode(carry);
    }
    
    return zeroNode.next;
};

About Nilesh Raut

I am Nilesh,3+ years Exp of SEO, content writing, and keyword research. Also rocks it as a software dev with skills in OS, web dev, Flask, Python, C++, data structures, and algorithms. 3 on Leetcode, 5*on Hackerrank more platform.

4 thoughts on “Leet Code : Add Two List – Java | CPP | Javascript | Python”

  1. Hello,

    We can skyrocket your Google rankings in a short time with completely whitehat links and technical seo service.

    Please check our profile on fiverr:

    Please check tons of 5 star reviews on our Fiverr gig

  2. Hi,

    This AI content writer is less than $90 one time payment for lifetime usage. You can write engaging articles, product descriptions, social media posts, emails, company bio, stories, ads, and 57 other content categories in minutes.

    It is trained by Jasper AI data and 100M articles and scientific journals and uses the same tech (GPT3):

    https://appsumo.8odi.net/Ao4BDo

  3. Hi nileshblog.tech team,

    I can rank your webpages on the first page (the top 3 rankings) of Google with on page and off page SEO service that follows Google guidelines. Never lose your rankings.

    Monthly packages include:

    On Page :

    – Content Optimization
    – Images optimization
    – Meta Tags and H1,H2 Optimization
    – Permalink Set Up
    – Fix Broken Links or 404 Errors
    – Create XML Sitemap
    – Fix Canonical Issue
    – Speed Optimization

    Off Page:

    – Omnichannel Marketing
    – High quality backlinks from domains with real visitors

    Let me know if you have any questions. Rank your webpages now.

  4. Hi there,

    I will develop a unique and bug-free top-level NFT website for you: NFT minting website, smart contract and web 3 integration

    NFT minting functionality
    Smart contract development (erc721, erc721a, erc1155)
    Listing on Opensea and Rarible
    Connect wallet functionality
    NFT metadata generation ( art is provided by you )
    NFT metadata upload to IPFS
    Whitelist/Presale using merkle tree technology
    Ability to mint directly with credit card

    Blockchains:

    Solana
    Ethereum
    Polygon
    Binance Smart Chain
    Avalanche

    Website Frontend:

    React JS / Next JS

    Some reviews:

    “By far one of the best developers, I have come across and went above and beyond to make sure that everything was perfect for our launch. Great communication and a will to do things the right way. Will definitely be using again and HIGHY RECCOMEND!”

    “It’s my second time ordering from him I needed a front page for my website this time and Josiah did a stellar job with the UI and coding. If you’re looking for a detail-oriented dev who knows what he’s doing, this is definitely the place to go.”

    “He did an amazing job for us, I can highly recommend him! He explained us everything and everything worked as described! If you search someone for your NFT project, do it with him!”

Leave a Comment

Discover more from NileshBlog.Tech

Subscribe now to keep reading and get access to the full archive.

Continue Reading