-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAddTwoNumber.ts
46 lines (39 loc) · 1.06 KB
/
AddTwoNumber.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
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)
}
}
function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
if (l1 == null || l2 == null) {
return null;
}
const dummyHead = new ListNode(0);
let current = dummyHead;
let carry = 0;
while (l1 !== null || l2 !== null || carry > 0) {
if (l1) {
carry += l1.val;
l1 = l1.next
}
if (l2) {
carry += l2.val;
l2 = l2.next
}
current.next = new ListNode(carry%10);
current = current.next;
carry = Math.floor(carry / 10);
}
return dummyHead.next;
};
// Test case
const l1 = new ListNode(2);
l1.next = new ListNode(4);
l1.next.next = new ListNode(3);
const l2 = new ListNode(5);
l2.next = new ListNode(6);
l2.next.next = new ListNode(4);
const result = addTwoNumbers(l1, l2);
console.log(result);