[프로그래머스] [C++] 가장 큰 수 (sort)

2021. 3. 18. 22:45알고리즘/프로그래머스

1. 문제

정수가 담긴 배열이 주어진다.

 

이 정수를 전부 문자열로 덧붙인다고 할때

 

숫자가 최대가 되게 하여라.

 

 

 

 

2. 비교함수 작성

이 문제는 비교함수에서 정수를 to_string으로 문자열로 변환하고 문자열을 + 연산하여

 

사전순으로 큰지 작은지 비교할 수 있다.

 

이는 아스키 코드상에서 문자 '0' ~ '9' 의 상대적 크기가 숫자 0 ~ 9 와 같기때문에 가능한 일이다.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <string>
#include <vector>
#include <algorithm>
 
using namespace std;
 
bool comp(const int& a, const int& b)
{
    string sa = to_string(a), sb = to_string(b);
    return sa+sb < sb+sa;
}
 
string solution(vector<int> numbers) {
    string answer = "";
    sort(numbers.begin(), numbers.end(), comp);
    for(int i = numbers.size() -1 ; 0 <= i ; i--)
        if(!(answer == "0" && numbers[i] == 0))
            answer += to_string(numbers[i]);
 
    return answer;
}
cs

 

 

 

 

3. 반성

복잡하게 문자 하나하나 비교해가면서 하는 풀이를 생각하였지만

 

단순한 해결법이 있었다.

 

 

 

 

코딩테스트 연습 - 가장 큰 수 | 프로그래머스 (programmers.co.kr)