반응형
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

string solution(vector<int> numbers) 
{    
    vector<string> strNumbers;
    for(int n : numbers)
        strNumbers.push_back(to_string(n));
    
    sort(strNumbers.begin(), strNumbers.end(), [](const string& a, const string& b) {
        return a + b > b + a;   // a+b가 b+a보다 크면 a가 앞에 오도록
    });
    
    string answer = "";
    for(string& s : strNumbers)
        answer += s;
    
    // 전부 0인 경우 ("00...0"이 아니라 "0"을 반환해야 함) 예외 처리
    if(answer[0] == '0') return "0";
    
    return answer;
}

 

해설:

정수가 들어있는 배열을 가장 큰 수로 조합하여 문자로 반환해야한다.

먼저 string으로 변환할 수 있게 to_string()을 이용해야 한다. 그리고 sort를 이용하기 위해 #include<algorithm>을 추가해야 한다. 여기서 중요한건 람다식이다. a, b를 배열에 있는 값들을 받아 return a + b > b + a;를 비교하여 가장 큰 값을 반환하여 정렬시킨다. 이제 정렬이 완료되었으므로 문자열을 다 붙여서 반환하면 끝.

반응형

+ Recent posts