-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.add-two-numbers.js
133 lines (90 loc) · 2.23 KB
/
2.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
* @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}
*/
var addTwoNumbers = function (l1, l2) {
// 1. Use while loop to traverse l1 and l2
// 2. Add two numbers as I traverse and if it exceeds 10, then add 1 to next step
// 3. As I traverse, create add a node to a new list for output.
let output = new ListNode(0);
let head = output;
let anchor = 0;
while(l1 || l2){
let sum = anchor;
anchor = 0;
if(l1){
sum += l1.val;
l1 = l1.next;
}
if(l2){
sum += l2.val;
l2 = l2.next;
}
if(sum >= 10){
anchor = 1;
sum -= 10;
}
head.next = new ListNode(sum);
head = head.next;
}
if(anchor === 1){
head.next = new ListNode(anchor)
}
return output.next;
};
function ListNode(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
const listMaker = (arr) =>{
let list = new ListNode(0)
let head = list;
for(let i of arr){
head.next = new ListNode(i);
head = head.next;
}
return list.next;
}
let l1 = listMaker([9,9,9,9,9,9,9])
let l2 = listMaker([9,9,9,9])
addTwoNumbers(l1, l2);
// @lc code=end
/*
let list = new ListNode(0);
let head = list;
let sum = 0;
let carry = 0;
while(l1 !== null || l2 !== null || sum>0){
if(l1 !== null){
sum = sum + l1.val;
l1 = l1.next;
}
if(l2 !== null){
sum = sum + l2.val;
l2 = l2.next;
}
if(sum>=10){
carry = 1;
sum = sum - 10;
}
head.next = new ListNode(sum);
head = head.next;
sum = carry;
carry = 0;
}
return list.next;
*/