본문 바로가기
C++ 코딩 문제 풀이/프로그래머스

[Programmers] 최댓값과 최솟값

by 섬댕이 2023. 12. 28.

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

 

프로그래머스

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

programmers.co.kr

 


 

문제 해결 과정

착안

문자열의 마지막 문자에 도달하거나 공백이 나오기 이전까지의 문자를 숫자로 변형하여 하나씩 읽어가며 최솟값, 최댓값 여부를 판단한다.

 

구현

[스포 주의] 아래 '더보기'를 누르면 코드가 나오니 주의하세요~

더보기
#include <string>

using namespace std;

string solution(string s)
{
    int min = 2147483647;
    int max = -2147483648;
    
    while (s.size() > 0)
    {
        int end = 0;
        while (s[end] != ' ' && end != s.size() - 1)
            end++;
        
        int n = stoi(s.substr(0, end + 1));
            
        if (min > n)
            min = n;
            
        if (max < n)
            max = n;
            
        s = s.substr(end + 1);
    }
    
    return to_string(min) + " " + to_string(max);
}

 

실행 결과

댓글