0% found this document useful (0 votes)
2 views

Add Two Numbers

The document defines a Java class for adding two numbers represented by singly-linked lists. It includes a method that iterates through both lists, calculates the sum of corresponding digits along with any carry, and constructs a new linked list to represent the result. The method returns the head of the new linked list after processing all digits and carry.

Uploaded by

wedok26771
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Add Two Numbers

The document defines a Java class for adding two numbers represented by singly-linked lists. It includes a method that iterates through both lists, calculates the sum of corresponding digits along with any carry, and constructs a new linked list to represent the result. The method returns the head of the new linked list after processing all digits and carry.

Uploaded by

wedok26771
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

/**

* Definition for singly-linked list.


* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// solution
// step 1: define two new node dymmy and temp
// step 2: define carry as variable and assign the value as 0
// step 3: iiterate the while loop upto l1 is not null or l2 is not null or
carray equals to 1
// step 4: inside the loop define the sum variable and initalize it as 0
// step 5: check l1 is null or not if not null the add l1.val in sum and
push l1 next
// step 6: check l2 is null or not if not null then add l2.val in sum and
push l2 next
// step 7: add the carry into sum;
// step 8: calculate carry by deviding the sum by 10
// step 9: create the new node with the the value of sum of modulo 10
// step 10: temp.next to that new node
// step 11: incease temp to temp.next
// step 12: after the loop retrun the dummy.next

ListNode dummy= new ListNode();


ListNode temp=dummy;
int carry=0;

while(l1!=null || l2!=null || carry==1){


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);
temp.next=node;
temp=temp.next;
}
return dummy.next;
}
}

You might also like