Recently, I attempted the following leetCode Problem:
However, I encountered an issue where one of my test cases failed and I'm unsure why.
Here is the scenario:
You are provided with two non-empty linked lists that represent two non-negative integers. The digits are stored in reverse order, with each node containing a single digit. Your task is to add the two numbers and return the result as a linked list.
You can assume that the numbers do not contain any leading zeros, except for the number 0 itself.
To tackle this problem, I devised the following algorithm:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
const makeLinkedList = (inArr, i) => {
if (i < 0) return null
return { val:inArr[i], next:makeLinkedList(inArr, i-1)}
}
var addTwoNumbers = function(l1, l2) {
let sum = 0
let i = 1
while(l1 || l2) {
if (l1 && l2) {
sum = sum + l1.val*i + l2.val*i
l1 = l1.next
l2 = l2.next
} else {
if (l1) {
sum = l1.val*i + sum
l1 = l1.next
}
if (l2) {
sum = l2.val*i + sum
l2 = l2.next
}
}
i = i*10
}
const sumToString = sum.toLocaleString('fullwide', {useGrouping:false});
return makeLinkedList(sumToString, sumToString.length-1)
};
The reason behind using a while loop instead of recursive functions in the code above was mainly for optimization purposes.
However, I faced a challenge as my test case failed for the input below:
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[5,6,4]
My output returned as [0,3,NaN,NaN,1]
, rather than
[6,6,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
.
If anyone could assist me in identifying why my input might be failing, it would be greatly appreciated.