프로그래머스 가장 큰 수

문제

1

문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/42746

풀이

정수형 배열을 문자형 배열로 바꾸고 서로 더했을 때 더 큰 문자열을 구분하는 comp 함수를 이용한 정렬을 진행한다음 정답 배열에 append 시켜 리턴하도록 풀었다.

#include <string>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

bool comp(const string &a, const string &b)
{
	if (b + a < a + b)
		return true;
	return false;
}

string solution(vector<int> numbers)
{
	string answer = "";

	vector<string> str;
	


	for (int i = 0; i < numbers.size(); i++) // 정수들을 문자형 배열에 push
	{
		str.push_back(to_string(numbers[i]));
	}

	sort(str.begin(), str.end(), comp); // comp 함수를 이용한 sorting
	
	for (int i = 0; i < str.size(); i++) // 정렬된 문자들 append
	{
		answer += str[i];
	}
	if (answer[0] == '0') // 배열에 0만 들어있을 때 예외처리
	{
		return "0";
	}

	return answer;
}

댓글남기기