[프로그래머스] 가장 큰 수 | C++
Algorithm/문제풀이
2023. 1. 12. 15:28
문제
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
숫자들을 문자열로 조합한 후 가장 큰 값을 반환하는 문제이다.
풀이 전략
사용자 정의로 비교함수를 정의한다.
상세
1) numbers의 숫자들을 문자로 변환 후, vector<string> store에 저장해둔다.
더보기
string solution(vector<int> numbers)
{
string answer = "";
vector<string> store;
for(int number : numbers)
store.push_back(to_string(number));
}
2) store에 저장된 문자열들을 정렬할 것이다.
정렬기준은 직접 함수 cmp()로 정의한다.
두 문자열이 주어질 때 합을 비교한 후, 큰 문자열을 반환하도록 하자.
더보기
bool cmp(string& a, string& b)
{
return a + b > b + a;
}
3) cmp()를 기준으로 정렬을 수행한다.
정렬 후 answer에 삽입해준다.
더보기
sort(store.begin(), store.end(), cmp);
for(string item : store)
answer += item;
4) 주의할 점이 있다.
answer에 '0'만 여러개 들어간다면
answer는 '000 ... 0'이 아닌 '0'을 반환해주도록 해야한다는 것이다.
answer[0]이 '0'인지 확인되면, answer를 "0"으로 설정해주자.
0이 여러개 있는데, 그중 다른 숫자가 하나라도 있기만 해도
answer[0]은 0이 아니게 된다.
더보기
if(answer[0] == '0')
answer = "0";
전체 소스코드
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
bool cmp(string& a, string& b)
{
return a + b > b + a;
}
string solution(vector<int> numbers)
{
string answer = "";
vector<string> store;
for(int number : numbers)
store.push_back(to_string(number));
sort(store.begin(), store.end(), cmp);
for(string item : store)
answer += item;
if(answer[0] == '0')
answer = "0";
return answer;
}
int main()
{
return 0;
}
'Algorithm > 문제풀이' 카테고리의 다른 글
[프로그래머스] 최솟값 만들기 | C++ (0) | 2023.02.18 |
---|---|
[프로그래머스] 연속 부분 수열 합의 개수 | C++ (0) | 2023.01.14 |
[프로그래머스] 모음사전 | C++ (0) | 2023.01.12 |
[프로그래머스] 피로도 | C++ (0) | 2023.01.11 |
[프로그래머스] 소수 찾기 | C++ (2) | 2023.01.07 |