-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetSum.js
More file actions
30 lines (23 loc) · 876 Bytes
/
getSum.js
File metadata and controls
30 lines (23 loc) · 876 Bytes
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
/*
Given two integers a and b, which can be positive or negative, find the sum of all the integers between and including them and return it. If the two numbers are equal return a or b.
Note: a and b are not ordered!
Examples (a, b) --> output (explanation)
(1, 0) --> 1 (1 + 0 = 1)
(1, 2) --> 3 (1 + 2 = 3)
(0, 1) --> 1 (0 + 1 = 1)
(1, 1) --> 1 (1 since both are same)
(-1, 0) --> -1 (-1 + 0 = -1)
(-1, 2) --> 2 (-1 + 0 + 1 + 2 = 2)
Your function should only return a number, not the explanation about how you get that number.
*/
function getSum(a, b){
let arr = []; //Array to store numbers between a & b
let min = Math.min(a,b)
let max = Math.max(a,b)
//Minimum and Maximum numbers between a & b
for(let i = min; i <= max; i++ ){
arr.push(i)
} //Loop to
return arr.reduce((acc, cumm) => acc + cumm, 0)
}
console.log(getSum(1,0));