Skip to content

Commit 8c68735

Browse files
committed
solved: 2
1 parent 28327ac commit 8c68735

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

code/2.add-two-numbers.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* val: number
5+
* next: ListNode | null
6+
* constructor(val?: number, next?: ListNode | null) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
* }
11+
*/
12+
13+
function addTwoNumbers(
14+
l1: ListNode | null,
15+
l2: ListNode | null,
16+
carry: number = 0,
17+
): ListNode | null {
18+
if (!l1 && !l2 && carry === 0) {
19+
return null;
20+
}
21+
22+
const firstNum = l1 ? l1.val : 0;
23+
const secondNum = l2 ? l2.val : 0;
24+
const summation = firstNum + secondNum + carry;
25+
26+
carry = Math.floor(summation / 10);
27+
const num = summation % 10;
28+
29+
const currentNode = new ListNode(num);
30+
currentNode.next = addTwoNumbers(
31+
l1 ? l1.next : null,
32+
l2 ? l2.next : null,
33+
carry,
34+
);
35+
36+
return currentNode;
37+
}

0 commit comments

Comments
 (0)