[codewars] Beginner Series #3 Sum of Numbers

KJA·2022년 8월 29일
0

https://www.codewars.com/kata/55f2b110f61eb01779000053/javascript


Description

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!

Example

(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) {
    if (a === b) return a;
    else{
        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;
    }
}

다른 풀이

const GetSum = (a, b) => {
  let min = Math.min(a, b),
      max = Math.max(a, b);
  return (max - min + 1) * (min + max) / 2;
}
function GetSum(a, b) {
   if (a == b) return a;
   else if (a < b) return a + GetSum(a+1, b);
   else return a + GetSum(a-1,b);
}

0개의 댓글