문제
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"
참조
'Programmers' 카테고리의 다른 글
| [프로그래머스] 기능 개발 (JS) (0) | 2023.11.12 |
|---|---|
| [프로그래머스] 같은 숫자는 싫어 (JS) (0) | 2023.11.12 |
| [프로그래머스] K번째수 (JS) - sort (0) | 2023.11.10 |
| [프로그래머스] 소수 찾기 (JS) - 완전탐색, DFS (1) | 2023.11.09 |
| [프로그래머스] 모의고사 (JS) - 완전탐색 (0) | 2023.11.09 |