As I work on the exercise found at , I have devised a solution that has been successfully tested with smaller arrays containing around 5-7 elements.
class ListNode {
val: number
next: ListNode | null
constructor(val?: number, next?: ListNode | null) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
}
var l1 = new ListNode(1, new ListNode(0, new ListNode(0, new ListNode(0, new ListNode(0, new ListNode(0, new ListNode(0, new ListNode(0, new ListNode(0, new ListNode(0, new ListNode(0, new ListNode(0, new ListNode(0, new ListNode(0, new ListNode(0, new ListNode(0, new ListNode(0, new ListNode(0 , new ListNode(0, new ListNode(0 , new ListNode(0, new ListNode(1)))))))))))))))))))));
var l2 = new ListNode(5, new ListNode(6, new ListNode(4)));
function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
let r1 = [], r2 = [];
while(l1 !== null)
{
r1.push(l1.val);
l1 = l1.next;
}
while(l2 !== null)
{
r2.push(l2.val);
l2 = l2.next;
}
console.log(r1); console.log(r2);
r1.reverse(); r2.reverse();
let n1, n2;
n1 = Number(r1.join(''))
n2 = Number(r2.join(''))
let n3 = n1 + n2;
let newN3 = n3.toString().split('').reverse();
console.log(`N1: ${n1} N2: ${n2} N3: ${n3} newN3: ${newN3.toString()}`);
let l3 : ListNode[] = [];
for(let i = 0 ; i < newN3.length ; i ++)
l3.push(new ListNode(Number(newN3[i]),null));
for(let i = 0 ; i < l3.length ; i++)
l3[i].next = l3[i+1]??null;
return l3[0];
};
let salida = addTwoNumbers(l1,l2);
console.log(salida);
while(salida !== null)
{
console.log('Num; ', salida.val);
salida = salida.next;
}
Upon further testing with the 21-element array l1
, it appears that the last element of the array is being ignored. The output shows:
[
1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1
]
[ 5, 6, 4 ]
N1: 100000000000000000000 N2: 465 N3: 100000000000000000000 newN3: 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1
ListNode {
val: 0,
next: ListNode { val: 0, next: ListNode { val: 0, next: [ListNode] } }
}
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 0
Num; 1
It should be noted that N1 should be 100000000000000000001, but it currently outputs as 100000000000000000000. The sum of N1+N2 is also incorrect.