- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddTwoNumbers.ts
52 lines (45 loc) · 1.15 KB
/
addTwoNumbers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
classListNode{
val: number;
next: ListNode|null;
constructor(val?: number,next?: ListNode|null){
this.val=val??0;
this.next=next??null;
}
}
functionlistNodeToArray(node: ListNode|null): number[]{
constresult: number[]=[];
while(node){
result.push(node.val);
node=node.next;
}
returnresult;
}
functionarrayToListNode(arr: number[]): ListNode|null{
if(arr.length===0)returnnull;
consthead=newListNode(arr[0]);
letcurrent=head;
for(leti=1;i<arr.length;i++){
current.next=newListNode(arr[i]);
current=current.next;
}
returnhead;
}
functionaddTwoNumbers(
l1: ListNode|null,
l2: ListNode|null
): ListNode|null{
constarr1=listNodeToArray(l1);
constarr2=listNodeToArray(l2);
constresult: number[]=[];
letcarry=0;
leti=0;
while(i<arr1.length||i<arr2.length||carry>0){
constdigit1=i<arr1.length ? arr1[i] : 0;
constdigit2=i<arr2.length ? arr2[i] : 0;
constsum=digit1+digit2+carry;
result.push(sum%10);
carry=Math.floor(sum/10);
i++;
}
returnarrayToListNode(result);
}