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

[Codewars] Highest and Lowest (7 kyu) / JavaScript

by fluss 2022. 10. 27.

https://www.codewars.com/kata/554b4ac871d6813a03000035

 

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:

In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.

 

Examples

highAndLow("1 2 3 4 5");  // return "5 1"
highAndLow("1 2 -3 4 5"); // return "5 -3"
highAndLow("1 9 3 4 -5"); // return "9 -5"

 

Notes

  • All numbers are valid Int32, no need to validate them.
  • There will always be at least one number in the input string.
  • Output string must be two numbers separated by a single space, and highest number is first.
 
 

설명:

이 작은 과제에서는 공백으로 나누어진 숫자들의 문자열이 주어지고 가장 큰 숫자와 가장 작은 숫자를 반환해야 합니다.

 

예시

highAndLow("1 2 3 4 5");  // return "5 1"
highAndLow("1 2 -3 4 5"); // return "5 -3"
highAndLow("1 9 3 4 -5"); // return "9 -5"

 

참고

  • 모든 숫자는 유효한 int32이며 유효성을 검사할 필요가 없습니다.
  • 입력된 문자열은 최소한 하나의 숫자를 가지고 있습니다.
  • 출력 문자열은 반드시 하나의 공백으로 구분된 두 숫자여야하며 큰 숫자가 먼저 옵니다.

 

풀이

 문자열을 공백을 기준으로 나누어 배열을 만들어주고 Math.max와 Math.min을 이용해 최댓값과 최솟값을 구해서 반환했다.

 

코드

function highAndLow(numbers){
  numbers = numbers.split(' ').map(el => parseInt(el));
  return Math.max(...numbers) +' '+ Math.min(...numbers);
}

 

참고

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

 

Math.max() - JavaScript | MDN

The Math.max() function returns the largest of the numbers given as input parameters, or -Infinity if there are no parameters.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min

 

댓글