본문 바로가기

코딩테스트/프로그래머스

[프로그래머스] 가장 큰 수

728x90
반응형


🔗 문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/42746

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


728x90
반응형

👩‍💻 코드

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

struct CustomCompare{
    bool operator()(const string & a, const string & b) const {
        return a + b > b + a;
    }   
};

string solution(vector<int> numbers) {
    string answer = "";
    vector<string> numbersStr;
    
    if(all_of(numbers.begin(), numbers.end(), [](int x) {return x == 0;})){
        return "0";
    }
    
    for(auto number : numbers){
        numbersStr.push_back(to_string(number));
    }
    
    sort(numbersStr.begin(), numbersStr.end(), CustomCompare());
    
    for(auto n : numbersStr){
        answer += n;
    }
    
    return answer;
}

📝 풀이

int형식으로 되어 있는 숫자들은 string으로 바꿉니다.

두 숫자를 이어붙혔을 때 더 큰 값을 반환하는 커스텀 비교 함수를 정의합니다.

sort를 사용하여 정렬한 후 answer에 순서대로 이어붙혀 return 합니다.

 

주의! 모든 숫자가 0인 예외처리를 추가합니다.

728x90
반응형