<문제>
https://school.programmers.co.kr/learn/courses/30/lessons/12939
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문자열 s에는 공백으로 구분된 숫자들이 저장되어 있습니다. str에 나타나는 숫자 중 최소값과 최대값을 찾아 이를 "(최소값) (최대값)"형태의 문자열을 반환하는 함수, solution을 완성하세요.예를들어 s가 "1 2 3 4"라면 "1 4"를 리턴하고, "-1 -2 -3 -4"라면 "-4 -1"을 리턴하면 됩니다.
제한 조건
s에는 둘 이상의 정수가 공백으로 구분되어 있습니다.
<제출답안>
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cctype>
using namespace std;
string solution(string s) {
string answer = "";
int s_int;
int s_length;
vector<int> s_int_vector;
while(s.size()!=0)
{
if(isspace(s[0])!=0)
{
s.erase(s.begin());
continue;
}
s_int = stoi(s);
s_int_vector.push_back(s_int);
s_length = to_string(s_int).size();
// cout<<s_length<<endl;
while(s_length!=0)
{
s.erase(s.begin());
s_length --;
}
}
sort(s_int_vector.begin(),s_int_vector.end());
answer += to_string(s_int_vector[0])+" "+to_string(s_int_vector[s_int_vector.size()-1]);
return answer;
}
어렵지 않은 정렬 문제이다.
내 풀이는 다음과 같다.
1-1. 빈칸이면 그냥 제거
1-2. 빈칸이 아닐 경우 -> 정수화 시켜서 vector에 넣음,
그후 - 부호 포함 자릿수를 구하여 (to_string().size() 를 사용) 그 길이 만큼 제거해줌
2. sort 시켜줌
3. 가장 작은 값과 가장 큰 값 출력