티스토리 뷰
https://programmers.co.kr/learn/courses/30/lessons/42746?language=cpp#
코딩테스트 연습 - 가장 큰 수
0 또는 양의 정수가 주어졌을 때, 정수를 이어 붙여 만들 수 있는 가장 큰 수를 알아내 주세요. 예를 들어, 주어진 정수가 [6, 10, 2]라면 [6102, 6210, 1062, 1026, 2610, 2106]를 만들 수 있고, 이중 가장 큰
programmers.co.kr
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct{
bool operator()(string a, string b) const{
return a+b>b+a;
}
} cmp;
string solution(vector<int> numbers) {
string answer = "";
vector<string> sorted_numbers;
for (int n : numbers)
sorted_numbers.push_back(to_string(n));
sort(sorted_numbers.begin(), sorted_numbers.end(), cmp);
if (sorted_numbers[0]=="0") return "0";
for (string s: sorted_numbers){
answer+=s;
}
return answer;
}
처음엔 operator() 함수를 while 문 써서 자릿수끼리 비교하는 걸로 했다가.. 계속 오류떴다..
찾아보니 더 간단한 방법이 있었다. 문자열 2개를 a+b, b+a 이렇게 붙인 다음에 큰 값 순으로 정렬해주는 방식. 이러면 (30, 3) 이 있다 했을때 330>303 자연스럽게 먼저 정렬된다. 붙여서 비교해서 정렬하는 문제였다!!
'Problem Solving' 카테고리의 다른 글
[프로그래머스] 프린터 (C++) (0) | 2021.10.27 |
---|---|
[BOJ 21609] 상어 중학교 (C++) (0) | 2021.10.21 |
[프로그래머스] 카펫 (C++) (0) | 2021.10.21 |
[프로그래머스] 위장 (Python3) (0) | 2021.10.21 |
[BOJ 19236] 청소년 상어 (C++) (0) | 2021.10.20 |