본문 바로가기
알고리즘/Codewars

[Codewars] Sum Arrays (8 kyu) / JavaScript

by fluss 2022. 10. 12.

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에 입력받은 배열의 원소를 하나하나 더하고 다 더한 값을 반환한다. 

댓글