Leetcode Add Two Numbers problem solution in Java programming

In the Leetcode Add Two Numbers problem solution in Java programming You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Leetcode Add Two Numbers problem solution in Java programming

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        
        ListNode ans = new ListNode();
        ListNode pointer = ans;
      
        
        while(l1 != null && l2 != null){
            
            
            //when overflow 
            if(l1.val + l2.val + pointer.val >= 10){
                pointer.next = new ListNode(1);
            }
            //when no overflow 
            else{
                if(l1.next != null || l2.next != null)
                    pointer.next = new ListNode(0);
            }
            
            pointer.val = ((l1.val + l2.val + pointer.val)%10);
            
            pointer = pointer.next;
            l1 = l1.next;
            l2 = l2.next;
            
        }
        
        while(l1 != null){
            
            
            //when overflow
            if(l1.val + pointer.val >= 10){
                pointer.next = new ListNode(1);
            }
            
            //when no overflow
            else{
                if(l1.next != null)
                    pointer.next = new ListNode(0);
            }
            
            pointer.val = ((l1.val + pointer.val)%10);
            pointer = pointer.next;
            l1 = l1.next;

        }
           
         while(l2 != null){
            
            
            //when overflow
            if(l2.val + pointer.val >= 10){
                pointer.next = new ListNode(1);
            }
            
            //when no overflow
            else{
                if(l2.next != null)
                    pointer.next = new ListNode(0);
            }
            
            pointer.val = ((l2.val + pointer.val)%10);
            pointer = pointer.next;
            l2 = l2.next;

        }
        
           
        return ans;
    }
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *