(codeWars) Highest and Lowest

호두파파·2021년 2월 24일
0

알고리즘 연습

목록 보기
5/60
post-thumbnail

Description:

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

Example:

  • 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.

음수와 양수를 담고있는 문자열을 파라미터로 주었을 때 가장 큰수와 가장 작은 수를 포함한 문자열을 반환하는
솔루션을 작성하는 문제


문제풀이

문제를 보자마자, sort()를 이용해서 문제를 해결해야 함을 직감했다. 하지만 sort()는 함수는 양의 수를 가진 배열만 정렬하기 때문에, 음수를 함께 정렬하기 위해서 별도의 식을 구성해야 했다.

map() 메소드를 이용해서 문자열를 숫자로 바꿔 새로운 배열을 만들어준다. 생성된 배열을 바탕으로 다시 sort()를 이용해 리턴값을 설정한다.

parseInt()함수는 문자열 인자를 구문 분석해 특정 진수(수의 진법 체계에 기준이 되는 값)의 정수를 반환한다.

function hignAndLow(numbers) {
  let sort;
  let result = "";
  let array = numbers.split(" ").map(n => parseInt(n, 100)); 
  sort = array.sort((a, b) => {
    return a - b
  });
  return result = sort[sort.length -1] + " " + sort[0];

다른 문제 풀이

function highAndLow(numbers){
  numbers = numbers.split(' ').map(Number);
  return Math.max.apply(0, numbers) + ' ' + Math.min.apply(0, numbers);
}

sort()를 사용하지 않고도, 최대값과 최소값을 뽑아내는 메소드를 이용해서 풀이한 답안,
영리하다.

profile
안녕하세요 주니어 프론트엔드 개발자 양윤성입니다.

0개의 댓글