Coding Test - cpp/Sort
[프로그래머스 lv 2 ] - 가장 큰 수
에드윈H
2021. 4. 21. 20:22
programmers.co.kr/learn/courses/30/lessons/42746?language=cpp
코딩테스트 연습 - 가장 큰 수
0 또는 양의 정수가 주어졌을 때, 정수를 이어 붙여 만들 수 있는 가장 큰 수를 알아내 주세요. 예를 들어, 주어진 정수가 [6, 10, 2]라면 [6102, 6210, 1062, 1026, 2610, 2106]를 만들 수 있고, 이중 가장 큰
programmers.co.kr
cmp 함수 사용
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
bool cmp(string a, string b) {
return a + b > b + a;
}
string solution(vector<int> numbers) {
string answer = "";
vector<string> temp;
for (auto num : numbers)
{
temp.push_back(to_string(num)); //string 변환 저장
}
sort(temp.begin(), temp.end(), cmp); //정렬하는데 더큰값이 먼저오게 ex) 3과 30이 있다면 330이 큰지 303이 큰지
if (temp.at(0) == "0")
{
return "0";
}
for (auto num : temp )
{
answer += num;
}
return answer;
}
cmp 함수대신 람다식 사용
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
string solution(vector<int> numbers) {
string answer = "";
vector<string> temp;
for (auto num : numbers)
{
temp.push_back(to_string(num)); //string 변환 저장
}
//정렬하는데 더큰값이 먼저오게
sort(temp.begin(), temp.end(), [](string a, string b){ return a + b > b + a;});
if (temp.at(0) == "0")
{
return "0";
}
for (auto num : temp)
{
answer += num;
}
return answer;
}