[프로그래머스] 최댓값과 최솟값

hamsteak·2023년 9월 10일
0

ps

목록 보기
1/39

주어진 문자열에 정수들이 공백을 사이에 두고 주어진다. 공백이 아닌 문자를 버퍼에 추가하다가 문자가 공백 혹은 마지막 위치의 문자일 경우, 버퍼를 정수로 변환하고 최댓값, 최솟값을 갱신한 후에 다음 정수를 입력받기 위해 버퍼를 초기화한다.

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

cpp code

#include <string>
#include <vector>
#include <limits.h>

using namespace std;

string solution(string s) {
    string answer = "";
    
    int l = INT_MAX, r = INT_MIN;
    string buf;
    for (int i=0;i<s.length();i++) {
        if (s[i] != ' ') buf += s[i];
        
        if (s[i] == ' ' || i == s.length() - 1) {        
            int n = stoi(buf);
            l = min(l, n);
            r = max(r, n);
            buf = "";
        }
    }
    
    answer += to_string(l) + ' ' + to_string(r);
    
    return answer;
}
profile
안녕하세요

0개의 댓글