본문 바로가기
Develop/프로그래머스 (Cpp)

[프로그래머스] 최댓값과 최솟값 (C++)

by Tarra 2023. 3. 19.

최댓값과 최솟값 / Lv.2


문제  설명 )

문자열 s에는 공백으로 구분된 숫자들이 저장되어 있습니다. str에 나타나는 숫자 중 최소값과 최대값을 찾아 이를 "(최소값) (최대값)"형태의 문자열을 반환하는 함수, solution을 완성하세요.
예를들어 s가 "1 2 3 4"라면 "1 4"를 리턴하고, "-1 -2 -3 -4"라면 "-4 -1"을 리턴하면 됩니다.

 

 

 

제한 사항 )

  • s에는 둘 이상의 정수가 공백으로 구분되어 있습니다.

 

 

 

입출력 예 )

 

 

 

풀이)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
 
 
using namespace std;
 
string solution(string s) {
    string answer = "";
    
    // stringstream 사용
    stringstream ss;
    ss.str(s);
    
    vector<int> temp;
 
    // 버퍼 ss에서 word를 받는다.
    string word;
    while(ss >> word)
    {
        temp.push_back(stoi(word));
    }
    
    answer += to_string(*min_element(temp.begin(), temp.end())) 
        + " " + to_string(*max_element(temp.begin(), temp.end())) ;
    
    return answer;
}
cs

출처 : https://school.programmers.co.kr/learn/courses/30/lessons/12939

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr