홍시홍의 프로그래밍

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

알고리즘 문제풀이/프로그래머스

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

홍시홍 2020. 4. 18. 19:55

분류 : 정렬

 

요구사항

주어진 int형 배열을 조합하여 만들 수 있는 수 중에서 가장 큰 수 찾기

 

풀이

int를 string으로 변환하여 내림차순으로 정렬하면 된다고 생각했으나 2번째 예제에서 실패한다 330 > 303

검색해보니

a+b > b+a 로 정렬하니 된다

앞으로 auto형도 자주 써야 되겠다

auto는 뒤에 지정한 형의 데이터로 자동으로 변환되는거 같다

auto iter만 사용했는데 for문에서도 자주사용하기

 

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

using namespace std;
bool com(string a, string b) {
	if (a + b > b + a) return true;
	return false;
}
string solution(vector<int> numbers) {
	string answer = "";
	//int a = stoi(answer);
	vector<string> v;
	for (auto i : numbers) 
		v.push_back(to_string(i));
	
	sort(v.begin(), v.end(),com);
	
	for (auto i : v) 
		answer += i;
	
	if (answer[0] == '0') 
		answer = "0";
	return answer;
}

 

Comments