본문 바로가기

Programmers

[프로그래머스] 가장 큰 수 (JS) - sort

문제

https://school.programmers.co.kr/learn/courses/30/lessons/42746

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

코드

function solution(numbers) {
    const answer = numbers.map(n => String(n)).sort((a,b) => (b+a)-(a+b)).join('');
    
    return answer[0]==='0' ? '0':answer;
}

정리

string으로 대소 비교를 하기 위해 map을 사용해 원소를 string type으로 변경해준다.

const answer = numbers.map(n => String(n))

 

sort((a,b) => a-b)에서 a-b가 양수이면 배열의 순서를 바꾸고 음수이면 바꾸지 않는다.

이걸 생각해서 이 문제에 적용해보면 input이 [10, 100]라 하면 10100을 return 해야한다.

그럼 sort에서는 10100과 10010의 대소를 비교해 순서를 결정해야한다.

그래서 다음과 같이 sort의 콜백을 정의할 수 있다.

.sort((a,b) => (b+a)-(a+b))

 

join method를 사용해 배열을 문자열로 변경한다.

.join('');

 

 

++ join

const animals = ['dog', 'cat', 'cow'];

console.log(animals.join());	// "dog,cat,cow"
console.log(animals.join(''));	// "dogcatcow"
console.log(animals.join('-'));	// "dog-cat-cow"

참조

https://velog.io/@hyorimm/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EA%B0%80%EC%9E%A5-%ED%81%B0-%EC%88%98-in-JavaScript

https://ddururiiiiiii.tistory.com/64