'What is happening with the last element of the array?
So, I'm trying to solve the excercise in https://leetcode.com/problems/add-two-numbers/
I came up with this solution (which I have tested succesfully with shorter arrays of about 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(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;
}
However, when I tried it with that 21-element l1 array, it seems that it ignores the last element from the array. The output of that is:
[
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
Note that N1 should be 100000000000000000001, and outputs 100000000000000000000. And the sum of N1+N2 is wrong.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
