-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd-two-numbers.js
More file actions
82 lines (71 loc) · 1.79 KB
/
add-two-numbers.js
File metadata and controls
82 lines (71 loc) · 1.79 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
// https://leetcode.com/problems/add-two-numbers/
function ListNode(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
// var addTwoNumbers = function (list1, list2) {
// const list3 = new ListNode();
// let prev = list3;
// let surplus = 0;
// let sum = 0;
// while (list1 || list2) {
// sum = (list1?.val || 0) + (list2?.val || 0) + surplus;
// if (sum >= 10) {
// prev.next = new ListNode(sum - 10);
// surplus = 1;
// } else {
// surplus = 0;
// prev.next = new ListNode(sum);
// }
// list1 = list1?.next || 0;
// list2 = list2?.next || 0;
// prev = prev.next;
// }
// if (surplus) {
// prev.next = new ListNode(1);
// }
// return list3.next;
// };
var addTwoNumbers = function (list1, list2) {
const listnode = new ListNode();
let head = listnode;
let carry = 0;
while (list1 || list2 || carry) {
let sum = carry;
if (list1) {
sum += list1.val;
list1 = list1.next;
}
if (list2) {
sum += list2.val;
list2 = list2.next;
}
carry = Math.floor(sum / 10);
head.next = new ListNode(sum % 10);
head = head.next;
}
return listnode.next;
};
// create first linked list: 1 -> 3 -> 10
var n3 = new ListNode(5, null);
var n2 = new ListNode(3, n3);
var n1 = new ListNode(1, n2);
var L1 = n1;
// create second linked list: 5 -> 6 -> 9
var n6 = new ListNode(9, null);
var n5 = new ListNode(6, n6);
var n4 = new ListNode(5, n5);
var L2 = n4;
addTwoNumbers(L1, L2);