-
Notifications
You must be signed in to change notification settings - Fork 0
/
add_2_numbers.js
48 lines (42 loc) · 1.04 KB
/
add_2_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
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function (l1, l2) {
let result = sumResult(l1, l2, 0);
return result;
};
var sumResult = function (l1, l2, additionalNumber) {
let result = getSum(l1?.val, l2?.val, additionalNumber);
if (!l1?.next && !l2?.next && !result?.additional) {
return {
val: result?.sum,
next: null
};
} else {
return {
val: result?.sum,
next: sumResult(l1?.next, l2?.next, result?.additional)
}
}
}
var getSum = function (a, b, additional) {
let newA = a ? a : 0;
let newB = b ? b : 0;
let additionalNew = additional ? additional : 0;
let result = {
sum: 0,
additional: 0
};
var sum = newA * 1 + newB * 1 + additionalNew * 1;
if (sum >= 10) {
let strSum = sum + '';
result.additional = strSum[0];
result.sum = strSum[1];
} else {
result.sum = sum;
result.additional = 0;
}
return result;
}