While working on a LeetCode problem, I came across the following scenario:
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 contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
During this process, I discovered the following algorithm:
function ListNode(val) {
this.val = val;
this.next = null;
}
//This function is called
var addTwoNumbers = function(l1, l2) {
let remainder = 0
let l3 = {}
let head = l3
while (l1 || l2 || remainder) {
let sum = remainder
function sumList (linkedList) {
if (linkedList) {
sum += linkedList.val
return linkedList.next
}
return null
}
l1 = sumList(l1)
l2 = sumList(l2)
if (sum>9) {
remainder = 1
sum -= 10
} else {
remainder = 0
}
head.next = new ListNode(sum)
head = head.next
}
return l3.next
};
At one point, I found myself questioning the purpose of l3 in this algorithm. It seems essential for its functionality.
For more details on the question, you can visit: