# 2 Add Two Numbers
Pseudocode:
ListNode ans = new ListNode(0)
while l1!=null && l2!=null
(l1+l2+carry) % 10, save the carry
if(l1==null)
concat rest of the node in l2
if(l2==null)
concat rest of the node in l1
if theres carry left, add a new listnode of carry
Code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode ans = new ListNode(0);
ListNode ptr = ans;
int carry = 0;
while(l1!=null && l2!=null){
int num = (l1.val+l2.val+carry) % 10;
carry = (l1.val+l2.val+carry)/10;
ptr.next = new ListNode(num);
ptr = ptr.next;
l1 = l1.next;
l2 = l2.next;
}
while(l1!=null){
ptr.next = new ListNode((l1.val+carry)%10);
carry = (l1.val+carry)/10;
ptr = ptr.next;
l1 = l1.next;
}
while(l2!=null){
ptr.next = new ListNode((l2.val+carry)%10);
carry = (l2.val+carry)/10;
ptr = ptr.next;
l2 = l2.next;
}
if(carry!=0)
ptr.next = new ListNode(carry);
return ans.next;
}
}