https://www.codewars.com/kata/53dc54212259ed3d4f00071c
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:
Write a function that takes an array of numbers and returns the sum of the numbers. The numbers can be negative or non-integer. If the array does not contain any numbers then you should return 0.
Examples
Input: [1, 5.2, 4, 0, -1]
Output: 9.2
Input: []
Output: 0
Input: [-2.398]
Output: -2.398
Assumptions
- You can assume that you are only given numbers.
- You cannot assume the size of the array.
- You can assume that you do get an array and if the array is empty, return 0.
What We're Testing
We're testing basic loops and math operations. This is for beginners who are just learning loops and math operations.
Advanced users may find this extremely easy and can easily write this in one line.
설명:
숫자 배열을 받아 숫자들의 합을 반환하는 함수를 반환하세요. 숫자는 음수일 수도 정수가 아닐 수도 있습니다. 만약 배열이 숫자를 포함하고 있지 않다면 0을 반환하세요.
예시
입력: [1, 5.2, 4, 0, -1]
출력: 9.2
입력: []
출력: 0
입력: [-2.398]
출력: -2.398
가정
- 숫자만 주어진다고 가정할 수 있습니다.
- 배열의 크기를 가정할 수 있습니다.
- 빈 배열을 받았다고 가정할 수 있습니다. 그 경우 0을 반환합니다.
테스트하는 것
풀이
function sum (numbers) {
let sum = 0;
for(let i = 0; i < numbers.length; i++){
sum += numbers[i];
}
return sum;
};
변수 sum을 0으로 설정하고 배열의 길이만큼 반복문을 돌려 sum에 입력받은 배열의 원소를 하나하나 더하고 다 더한 값을 반환한다.
'알고리즘 > Codewars' 카테고리의 다른 글
[Codewars] Return Negative (8 kyu) / JavaScript (0) | 2022.10.12 |
---|---|
[Codewars] Convert a Boolean to a String (8 kyu) / JavaScript (0) | 2022.10.12 |
[Codewars] Find the odd int (6 kyu) / JavaScript (0) | 2022.10.12 |
[Codewars] Holiday VI - Shark Pontoon (8 kyu) / JavaScript (0) | 2022.10.11 |
[Codewars] You're a square! (7 kyu) / JavaScript (0) | 2022.10.10 |
댓글