문제 설명
문자열 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" |
코드
#include <string>
#include <sstream>
#include <vector>
using namespace std;
string solution(string s)
{
string answer = "";
int min,max,num;
string word;
istringstream input(s);
getline(input, word, ' ');
min = stoi(word);
max = min;
num = 0;
while(getline(input, word, ' '))
{
num = stoi(word);
if(min > num) min = num;
if(max < num) max = num;
}
answer+=(to_string(min))+ " " + (to_string(max));
return answer;
}
참고자료
https://blockdmask.tistory.com/334
[C++] to_string 함수에 대해서 (int to string)
안녕하세요. BlockDMask 입니다. 지난번에는 string을 int로 변경하는 stoi 함수에 대해서 알아보았습니다. 오늘은 int를 string으로 변경하는 to_string 함수에 대해서 알아보겠습니다. (string -> int 로 변..
blockdmask.tistory.com
https://greenapple16.tistory.com/219
[C++] 문자열(string)을 특정 문자로 자르기
문자열을 sstream을 사용하여 특정 문자열로 구분하여 자르기 아래 코드는 공백 문자를 기준으로 자르는 방법 #include #include #include using namespace std; int main() { string fruit = "apple lemon grape..
greenapple16.tistory.com
'문제풀이(C++) > 프로그래머스[Level2]' 카테고리의 다른 글
[프로그래머스 Level2][C++] 행렬의 곱셈 (0) | 2022.01.06 |
---|---|
[프로그래머스 Level2][C++] N개의 최소공배수 (0) | 2021.11.26 |
[프로그래머스 Level2][C++] 최솟값 만들기 (0) | 2021.11.04 |
[프로그래머스 Level2][C++] 올바른 괄호 (0) | 2021.11.03 |
[프로그래머스 Level2][C++] 피보나치 수 (0) | 2021.10.29 |