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)
function getSum( a,b )
{
let result = [];
if (a > b)
result = new Array(a - b + 1).fill();
else
result = new Array(b - a + 1).fill();
result[0] = a;
for (let i = 0; i < result.length; i++) {
if (a > b)
result[i] = a - i
else
result[i] = a + i
}
return result.reduce((sum, cur) => sum + cur);
}
나는 a가 큰 경우와 b가 큰 경우를 따로 나눠 계산해 주었는데, 아래처럼 Math.abs
절대값으로 구해주거나
function GetSum(a,b)
{
return (Math.abs(a - b) + 1) * (a+b) / 2;
}
Math.min
, Math.max
로 구해줄 수도 있다.
const GetSum = (a, b) => {
let min = Math.min(a, b),
max = Math.max(a, b);
return (max - min + 1) * (min + max) / 2;
}