forked from chihungyu1116/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 14
/
2 Add Two Numbers.js
73 lines (56 loc) · 1.44 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
// You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
// Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
// Output: 7 -> 0 -> 8
// Amazon Microsoft Bloomberg Airbnb Adobe
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
// value reverse helps to asslign the first digit or both linklist
var addTwoNumbers = function(l1, l2) {
if(l1 === null || l2 === null){
return l1 || l2;
}
var result = new ListNode(0);
var cur = result;
var p = l1;
var q = l2;
var carry = 0;
while(p || q){
var qval;
var pval;
if(q){
qval = q.val;
q = q.next;
} else {
qval = 0;
}
if(p){
pval = p.val;
p = p.next;
} else {
pval = 0;
}
var val = qval + pval + carry;
if(val > 9){
carry = 1;
val %= 10;
} else {
carry = 0;
}
cur.next = new ListNode(val);
cur = cur.next;
}
if(carry !== 0){
cur.next = new ListNode(1);
}
return result.next;
};