-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddTwoNumbers.ts
More file actions
59 lines (51 loc) · 1.55 KB
/
addTwoNumbers.ts
File metadata and controls
59 lines (51 loc) · 1.55 KB
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
53
54
55
56
57
58
59
function addTwoNumbers(
l1: ListNode | null,
l2: ListNode | null
): ListNode | null {
let carry: number = 0;
let head: ListNode = new ListNode(0);
let current: ListNode = head;
while (l1 !== null || l2 !== null) {
let sum = (l1?.val || 0) + (l2?.val || 0) + carry;
if (sum > 9) {
carry = 1;
current.next = new ListNode(sum - 10);
} else {
carry = 0;
current.next = new ListNode(sum);
}
current = current.next;
if (l1 !== null) l1 = l1.next;
if (l2 !== null) l2 = l2.next;
}
if (carry) {
current.next = new ListNode(1);
}
return head.next;
}
// Test
import { expect } from "chai";
import { ListNode, LinkedList } from "../../structures/LinkedList";
describe("2. Add Two Numbers", () => {
it("can add", () => {
let l1 = new LinkedList([2, 4, 3]);
let l2 = new LinkedList([5, 6, 4]);
let l3 = new LinkedList([7, 0, 8]);
let result = addTwoNumbers(l1.head, l2.head);
expect(JSON.stringify(result)).to.equal(JSON.stringify(l3.head));
});
it("can add with carry over", () => {
let l1 = new LinkedList([5]);
let l2 = new LinkedList([5]);
let l3 = new LinkedList([0, 1]);
let result = addTwoNumbers(l1.head, l2.head);
expect(JSON.stringify(result)).to.equal(JSON.stringify(l3.head));
});
it("can add different lengths", () => {
let l1 = new LinkedList([1, 8]);
let l2 = new LinkedList([0]);
let l3 = new LinkedList([1, 8]);
let result = addTwoNumbers(l1.head, l2.head);
expect(JSON.stringify(result)).to.equal(JSON.stringify(l3.head));
});
});