Problem
- Given two integers a and b, which can be positive or negative, find the sum of all the numbers between including them too and return it.
- If the two numbers are equal, return a or b.
Solution 01
function getSum(a, b) {
if (a === b) {
return a;
} else if (a < b) {
min = a;
max = b;
} else {
min = b;
max = a;
}
let sum = 0;
for (let i = min; i <= max; i++) {
sum += i;
}
return sum;
}
getSum(1, 1); // 1
getSum(1, 2); // 3
getSum(1, 3); // 6
getSum(1, 4); // 10
getSum(-2, 2); // 0
getSum(-2, 3); // 3
getSum(4, -2); // 7
Solution 02
function getSum(a, b) {
const min = Math.min(a, b);
const max = Math.max(a, b);
let sum = 0;
for (let i = min; i <= max; i++) {
sum += i;
}
return sum;
}
getSum(1, 1); // 1
getSum(1, 2); // 3
getSum(1, 3); // 6
getSum(1, 4); // 10
getSum(-2, 2); // 0
getSum(-2, 3); // 3
getSum(4, -2); // 7
Math.min()
: 값이 가장 작은 수를 반환한다.
Math.max()
: 값이 가장 큰 수를 반환한다.
Solution 03
function getSum(a, b) {
if (a === b) return a;
const min = Math.min(a, b);
const max = Math.max(a, b);
return min + getSum(min + 1, max);
}
getSum(1, 1); // 1
getSum(1, 2); // 3
getSum(1, 3); // 6
getSum(1, 4); // 10
getSum(-2, 2); // 0
getSum(-2, 3); // 3
getSum(4, -2); // 7