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

[Codewars] Count of positives / sum of negatives (8 kyu) / JavaScript

by fluss 2022. 11. 1.

https://www.codewars.com/kata/576bb71bbbcf0951d5000044

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website 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 an array of integers.

Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers. 0 is neither positive nor negative.

If the input is an empty array or is null, return an empty array.

 

Example

For input [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15], you should return [10, -65].

 

설명:

정수의 배열이 주어집니다.

첫 번째 원소가 양수의 수이고 두 번째 원소가 음수의 합인 배열을 반환하세요. 0은 양수도 음수도 아닙니다.

만약 입력이 빈 배열이거나 null이면 빈 배열을 반환합니다.

 

예시

입력이 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15] 면, [10, -65]를 반환해야 합니다.

 

풀이

 빈 배열이거나 null일 경우 빈 배열을 반환했고 입력이 양수일때는 count를 하나씩 늘리고 음수일 때는 하나씩 더해주어 양수의 수와 음수의 합을 배열로 만들어 반환했다.

 

코드

function countPositivesSumNegatives(input) {
  let count = 0;
  let sum = 0;
  let result = [];
  if(input === null || input.length < 1) return result
  for(let i = 0; i < input.length; i++){
    if(input[i] > 0) count++;
    else sum += input[i];
  }
  result = [count, sum];
  return result;
}
 
 

댓글