https://school.programmers.co.kr/learn/courses/30/lessons/42746
문제 설명
0 또는 양의 정수가 주어졌을 때, 정수를 이어 붙여 만들 수 있는 가장 큰 수를 알아내 주세요.
예를 들어, 주어진 정수가 [6, 10, 2]라면 [6102, 6210, 1062, 1026, 2610, 2106]를 만들 수 있고, 이중 가장 큰 수는 6210입니다.
0 또는 양의 정수가 담긴 배열 numbers가 매개변수로 주어질 때, 순서를 재배치하여 만들 수 있는 가장 큰 수를 문자열로 바꾸어 return 하도록 solution 함수를 작성해주세요.
제한 사항
- numbers의 길이는 1 이상 100,000 이하입니다.
- numbers의 원소는 0 이상 1,000 이하입니다.
- 정답이 너무 클 수 있으니 문자열로 바꾸어 return 합니다.
입출력 예
numbers | return |
[6, 10, 2] | "6210" |
[3, 30, 34, 5, 9] | "9534330" |
해결 방법
1. numbers 배열을 문자열로 변환
2. sort를 이용해서 가장 큰 수 조합 만들기
>(b+a) - (a+b)를 했을 때 음수이면 (a+b)가 더 큰 것이므로 자리 유지, 양수이면 (b+a)가 더 큰 것이므로 b가 앞으로 오도록 한다.
3. 2번의 결과를 join으로 합친다.
4. 만약 [0, 0, 0]이라면 000이 아니라 0이 나와야 하므로 3번 결과의 0번째 인덱스 (000인 경우 첫 번째 0)가 0인 경우 '0'
을 리턴하고 0이 아니라면 결과 그대로 리턴하도록 한다.
전체 코드
function solution(numbers) {
const stringNumbers = numbers.map(String);
const MaxString = stringNumbers.sort((a, b) => (b+a) - (a+b)).join("");
return MaxString[0] === '0' ? '0' : MaxString;
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[JavaScript] 프로그래머스 탐욕법 #조이스틱 (0) | 2022.09.16 |
---|---|
[JavaScript] 프로그래머스 완전탐색 #피로도 (0) | 2022.09.16 |
[JavaScript] 프로그래머스 스택/큐 #다리를 건너는 트럭 (0) | 2022.09.15 |
[JavaScript] 프로그래머스 스택/큐 #프린터 (0) | 2022.09.12 |
[JavaScript] 프로그래머스 스택/큐 #기능개발 (0) | 2022.09.12 |