-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathadd-two-numbers.js
91 lines (78 loc) · 2.31 KB
/
add-two-numbers.js
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// https://leetcode.com/problems/add-two-numbers/
// Related Topics: Linked List, Math
// Difficulty: Easy
/*
Initial thoughts:
Creating a new linked list, we need to loop over the given
linked lists, adding their values and moving any remaining
carry to the next digit.
Keep in mind that some carry may remain after both the linked list
are completed. We need to add the remaining carry to the result if need be.
Time complexity: O(Max(n,m)) where n === l1.length and m === l2.length
Space complexity: O(Max(n,m)) where n === l1.length and m === l2.length
*/
var addTwoNumbers = function(l1, l2) {
let tempRes = l1 ? l1.val : 0;
tempRes += l2 ? l2.val : 0;
let carry = (tempRes / 10) | 0;
tempRes = tempRes % 10;
const head = new ListNode(tempRes);
let curr = head;
l1 = l1.next;
l2 = l2.next;
while (l1 !== null || l2 !== null) {
tempRes = l1 ? l1.val : 0;
tempRes += l2 ? l2.val : 0;
tempRes += carry;
carry = (tempRes / 10) | 0;
tempRes = tempRes % 10;
curr.next = new ListNode(tempRes);
curr = curr.next;
if (l1) l1 = l1.next;
if (l2) l2 = l2.next;
}
if (carry) curr.next = new ListNode(carry);
return head;
};
/*
Optimization:
Instead of calculating the first digit in the linked lists
before we enter the while loop, we can create a dummy node
at the beginning of our result linked list and return its
next node when the loop is completed.
This approach won't change time or space complexity but
it renders our code cleaner and prevents repetition.
Time complexity: O(Max(n,m)) where n === l1.length and m === l2.length
Space complexity: O(Max(n,m)) where n === l1.length and m === l2.length
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
let tempRes,
carry = 0;
const head = new ListNode(0);
let curr = head;
while (l1 !== null || l2 !== null) {
tempRes = l1 ? l1.val : 0;
tempRes += l2 ? l2.val : 0;
tempRes += carry;
carry = (tempRes / 10) | 0;
tempRes = tempRes % 10;
curr.next = new ListNode(tempRes);
curr = curr.next;
if (l1) l1 = l1.next;
if (l2) l2 = l2.next;
}
if (carry) curr.next = new ListNode(carry);
return head.next;
};