문제 링크
난이도 : Lv. 2
문제 내용
문제 설명
문자열 s에는 공백으로 구분된 숫자들이 저장되어 있습니다. str에 나타나는 숫자 중 최소값과 최대값을 찾아 이를 “(최소값) (최대값)“형태의 문자열을 반환하는 함수, solution을 완성하세요.
예를들어 s가 “1 2 3 4”라면 “1 4”를 리턴하고, “-1 -2 -3 -4”라면 “-4 -1”을 리턴하면 됩니다.
제한 조건
- s에는 둘 이상의 정수가 공백으로 구분되어 있습니다.
입출력 예
s | return |
---|---|
”1 2 3 4" | "1 4" |
"-1 -2 -3 -4" | "-4 -1" |
"-1 -1" | "-1 -1” |
문제 분석
string을 공백 기준 split 하기
stoi 사용해서 문자를 숫자로 바꾸기
순회 {
최소보다 작으면 최소값으로
최대보다 크면 최대값으로
}
최소값 띄고 최대값 return
작성한 코드
#include <string>
#include <vector>
#include <iostream>
using namespace std;
string solution(string s) {
string answer = "";
vector<int> arr;
long long pos = 0;
while((pos = s.find(" ")) != string::npos) {
string subs = s.substr(0, pos);
arr.push_back(stoi(subs));
s.erase(0, pos + 1);
}
arr.push_back(stoi(s));
int maxi = -10000000;
int mini = 10000000;
for(int a : arr) {
if(a > maxi) maxi = a;
if(a < mini) mini = a;
}
answer += to_string(mini);
answer += " ";
answer += to_string(maxi);
return answer;
}
우수 코드 분석
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string solution(string s) {
string answer = "";
string sTemp = "";
vector<int> vecInteger;
for (int i = 0; i < s.size(); i++)
{
if (s[i] == ' ')
{
vecInteger.push_back(stoi(sTemp));
sTemp.clear();
continue;
}
sTemp += s[i];
}
vecInteger.push_back(stoi(sTemp));
sort(vecInteger.begin(), vecInteger.end());
answer += to_string(vecInteger.front());
answer += ' ';
answer += to_string(vecInteger.back());
return answer;
}
Temp에다가 하나씩 넣어놓고 공백 발견할 때마다 그 Temp를 벡터로 넣음 그리고 정렬해서 최소/최대값 찾음.. 좋다