프로그래머스(Programmers)

정렬 > 가장 큰 수

cepiloth 2018. 9. 20. 17:27
반응형

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


1. 문제


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



2. 알고리즘

키워드 - 정렬, 구현


3. 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <algorithm>
#include <string>
#include <vector>
 
using namespace std;
 
bool comp(const string &a, const string &b)
{
    if (b + a < a + b)
        return true;
    return false;
}
 
string solution(vector<int> numbers) {
    string answer = "";
 
    vector<string> arr;
 
    for (int i=0; i<numbers.size(); i++) {
        arr.push_back(to_string(numbers[i]));
    }
 
    sort(arr.begin(), arr.end(), comp);
 
    for (auto iter = arr.begin(); iter < arr.end(); ++iter)
        answer += *iter;
 
    if (answer[0== '0')
        answer = "0";
 
    return answer;
}
cs



반응형