Problem Statement
Pattern:
Solution 1
Extra Linked List solution
public ListNode addTwoNumbers (ListNode l1, ListNode l2) {
ListNode ans = new ListNode(-1), ansHead = ans;
int carry = 0;
while (l1 != null || l2 != null || carry !=0) {
int first = (l1 != null) ? l1.val : 0;
int second = (l2 != null) ? l2.val : 0;
carry = carry + first + second;
ans.next = new ListNode(carry%10);
carry/=10;
// increment LLs
ans = ans.next;
l1 = (l1!=null) ? l1.next : null;
l2 = (l2!=null) ? l2.next : null;
}
return ansHead.next;
}
๐ this ones far better honestly. i spend so much time on ๐that, that i didnt have the heart to not note it down
Solution 2
Add sum into the second linked
public ListNode addTwoNumbers (ListNode l1, ListNode l2){
// p1 and p2 are dummy head l1 and l2s
ListNode p1 = new ListNode(-1, l1), p2 = new ListNode(-1, l2);
int carry = 0;
// while p1 and l2 left
while(p1.next != null && p2.next != null) {
carry = carry + p2.next.val + p1.next.val;
p2.next.val = carry % 10;
carry /=10;
p1 = p1.next;
p2 = p2.next;
}
// while p1 left
while(p1.next != null) {
carry = carry + p1.next.val;
p2.next = new ListNode(carry%10);
carry /=10;
p1 = p1.next;
p2 = p2.next;
}
// while l2 left
while (p2.next != null) {
carry = carry + p2.next.val;
p2.next.val = carry % 10;
carry /=10;
p2 = p2.next;
}
// while carry left
while(carry != 0) {
p2.next = new ListNode(carry%10);
carry /= 10;
p2 = p2.next;
}
return l2;
}