-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.add-two-numbers.js
More file actions
64 lines (62 loc) · 1.39 KB
/
2.add-two-numbers.js
File metadata and controls
64 lines (62 loc) · 1.39 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
60
61
62
63
64
/*
* @lc app=leetcode id=2 lang=javascript
*
* [2] Add Two Numbers
*/
// @lc code=start
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
function ListNode(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
var addTwoNumbers = function (l1, l2) {
let resultlist, head;
let carry = 0,
sum = 0;
let num1, num2;
while (l1 || l2 || carry === 1) {
num1 = l1 ? l1.val : 0;
num2 = l2 ? l2.val : 0;
sum = num1 + num2 + carry;
carry = 0;
if (sum >= 10) {
let newNode = new ListNode(sum % 10, null);
carry = 1;
if (resultlist) {
resultlist.next = newNode;
resultlist = resultlist.next;
} else {
resultlist = newNode;
head = newNode;
}
} else {
let newNode = new ListNode(sum, null);
if (resultlist) {
resultlist.next = newNode;
resultlist = resultlist.next;
} else {
resultlist = newNode;
head = newNode;
}
}
if (l1) l1 = l1.next;
if (l2) l2 = l2.next;
i++;
}
return head;
};
// @lc code=end
// @after-stub-for-debug-begin
module.exports = addTwoNumbers;
// @after-stub-for-debug-end