-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddTwoNumbers.js
48 lines (39 loc) · 1.04 KB
/
addTwoNumbers.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
/**
* https://leetcode.com/problems/add-two-numbers
* Time complexity - O(n + m)
* Space complexity - O(1) (excluding result)
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
let resultHead = new ListNode(-1);
let prev = resultHead;
let carry = 0;
while (l1 || l2) {
const l1Val = l1 ? l1.val : 0;
const l2Val = l2 ? l2.val : 0;
const sum = l1Val + l2Val + carry;
carry = sum > 9 ? 1 : 0;
const curr = new ListNode();
prev.next = curr;
curr.val = sum % 10;
prev = curr;
if (l1)
l1 = l1.next;
if (l2)
l2 = l2.next;
}
if (carry > 0) {
prev.next = new ListNode();
prev.next.val = carry;
carry = 0;
}
resultHead = resultHead.next;
return resultHead;
};
function ListNode(val, next) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
module.exports = { ListNode, addTwoNumbers }