https://www.codewars.com/kata/55f2b110f61eb01779000053
Codewars - Achieve mastery through coding practice and developer mentorship
Coding practice for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!
www.codewars.com
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!
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)
설명:
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.
양수 또는 음수 일수 있는 a와 b가 주어졌을 때 그 사이의 모든 정수와 그 정수의 합을 찾아서 반환합니다. 만약 두 수가 같다면 a 또는 b를 반환합니다.
주의: a와 b는 정렬되어있지 않습니다!
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 )
{
if(a === b){
return a;
}
let num1 = a;
let num2 = b;
let sum = 0;
if(a > b){
num1 = b;
num2 = a;
}
for(let i = num1; i <= num2; i++){
sum += i;
}
return sum;
}
a와 b 중 작은 수를 num1 큰 수를 num2에 넣어주고 num1부터 num2까지 하나씩 더해주는 방법으로 풀었다.
다른 사람의 좋았던 풀이
function GetSum(a,b)
{
return (Math.abs(a - b) + 1) * (a+b) / 2;
}
가우스 법칙을 사용해서 간단하게 풀 수 있었다.
'알고리즘 > Codewars' 카테고리의 다른 글
[Codewars] Convert boolean values to strings 'Yes' or 'No'. (8 kyu) / JavaScript (0) | 2022.10.01 |
---|---|
[Codewars] Simple Pig Latin (5 kyu) / JavaScript (2) | 2022.10.01 |
[Codewars] Binary Addition (7 kyu) / JavaScript (0) | 2022.09.29 |
[Codewars] Descending Order (7 kyu) / JavaScript (0) | 2022.09.28 |
[Codewars] Multiples of 3 or 5 (6 kyu) / JavaScript (0) | 2022.09.27 |
댓글