[프로그래머스/C++]Lv.0 - 컨트롤 제트

YH J·2023년 4월 18일
0

프로그래머스

목록 보기
41/168

문제 링크

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

내 풀이

한글자 한글자 하면서 숫자인지 공백인지 -인지 다 검사해서 계산했다. stringstream을 모를때라 이렇게 하였다.

내 코드

#include <string>
#include <vector>
#include <cctype>

using namespace std;

int solution(string s) {
    int answer = 0;
    int b = 0;
    int c = 0;
    bool m = false;
    for(const auto& a : s)
    {
        if(isdigit(a))
        {
            b = b * 10 + a - '0';
        }
        else if(a == '-')
        {
            m = true;
        }
        else if(a == 'Z')
        {
            answer -= c;
            b = 0;
        }
        else if(a == ' ')
        {
            if(m)
            {
                answer -= b;
                c = b * (-1);
            }
            else
            {
                answer += b;
                c = b;
            }
            m = false;
            b = 0;
        }
    }
    if(m)
        answer -= b;
    else
        answer += b;
    
    return answer;
}

다른 사람의 풀이

#include <string>
#include <vector>
#include <stack>
#include <sstream>

using namespace std;

int solution(string s) {
    int answer = 0;

    stringstream ss;
    ss.str(s);

    stack<int> st;

    int t = 0;
    string tmp = "0";
    while(ss>>tmp)
    {
        if(tmp == "Z")
        {
            st.pop();
        }
        else
        {        
            t = stoi(tmp);
            st.push(t);
        }
    }

    while(!st.empty())
    {
        answer += st.top();
        st.pop();
    }

    return answer;
}

다른 사람의 풀이 해석

stringstream을 사용하여 파싱하면서 stack에 숫자들을 넣는데 Z를만나면 최근에 넣은걸 pop시킨다. 굳이 빼는 연산 없이 그냥 pop해버리면 된다. 파싱이 끝나면 채워진 스택으로 합을 계산한다.

profile
게임 개발자 지망생

0개의 댓글