Coding Test - cpp/Sort
[프로그래머스 lv 2 ] - 가장 큰 수
에드윈H
2021. 4. 21. 20:22
programmers.co.kr/learn/courses/30/lessons/42746?language=cpp
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;
}