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

[Codewars] Sum of two lowest positive integers (7 kyu) / JavaScript

by fluss 2022. 12. 2.

https://www.codewars.com/kata/558fc85d8fd1938afb000014

 

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:

Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.

For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.

[10, 343445353, 3453445, 3453545353453] should return 3453455.

 

설명:

최소 4개의 양의 정수를 가지고 있는 배열이 주어지면 가장 작은 양의 정수 두 개를 더한 합을 반환하는 함수를 만드세요.

예를 들어, 배열이 [19, 5, 42, 2, 77]과 같이 전해지면, 출력은 7이 됩니다.

[10, 343445353, 3453445, 3453545353453]는 3453455을 반환합니다.

 

풀이

입력 받은 배열을 오름차순으로 정렬하고 처음 숫자와 두 번째 숫자를 더해서 반환했다.

 

코드

function sumTwoSmallestNumbers(numbers) {  
  numbers = numbers.sort((a, b) => a - b);
  return numbers[0] + numbers[1];
}

 

 

댓글