[algo / neet] 후위표기식 계산하기

데구리·3일 전

알고리즘

목록 보기
11/11

문제

문제 링크


C++ 정리

String/char ↔\leftrightarrow Number

  • "7" : 문자열 (String)
  • '7' : 문자 (Char)
변환함수 / 연산식비고
String →\rightarrow Intstd::stoi(str)문자열을 정수(int)로 변환 (String To Integer)
String →\rightarrow Long Longstd::stoll(str)문자열을 큰 정수(long long)로 변환 (String To Long Long)
String →\rightarrow Floatstd::stof(str)문자열을 단정밀도 실수(float)로 변환 (String To Float)
String →\rightarrow Doublestd::stod(str)문자열을 배정밀도 실수(double)로 변환 (String To Double)
Number →\rightarrow Stringstd::to_string()정수, 실수 등의 숫자를 문자열로 변환
Char →\rightarrow Numberc - '0'숫자 문자의 ASCII 값에서 '0'(48)을 빼서 정수로 변환
Number →\rightarrow Charnum + '0'0~9 사이의 정수에 '0'(48)을 더해 숫자 문자로 변환

최종 코드

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> st;
        int x1, x2;

        for (auto& c : tokens) {
            if (c == "*" || c == "/" || c == "+" || c == "-") {
                x2 = st.top(); st.pop();
                x1 = st.top(); st.pop();
                if (c == "*") st.push(x1*x2);
                else if (c == "/") st.push(x1/x2);
                else if (c == "+") st.push(x1+x2);
                else if (c == "-") st.push(x1-x2);
            }
            else st.push(stoi(c));
        }

        return st.top();
    }
};

풀이

  • 스택 사용해서 왼 → 오 읽기
  • 숫자는 스택에 push
  • 연산자일 경우
    - 스택에서 숫자 2개 pop
    - 연산 결과를 다시 스택에 넣기
  • 스택의 top 이 최종 연산 결과가 됨

코드 개선하기

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> st;
        int x1, x2;

        for (const auto& c : tokens) {
            if (c == '*' || c == '/' || c == '+' || c == '-') {
                x2 = st.top(); st.pop();
                x1 = st.top(); st.pop();

                switch (c) {
                    case '*': st.push(x1*x2); break;
                    case '/': st.push(x1/x2); break;
                    case '+': st.push(x1+x2); break;
                    case '-': st.push(x1-x2); break;
                }
            }
            else st.push(stoi(token));
        }

        return st.top();
    }
};
  • for (auto& c : tokens) 대신 for (const auto& token : tokens)를 사용: 문자열 복사 비용 방지(읽기 전용 reference)
  • switch 문 사용: if-else 중복 검사를 줄이고 가독성 좋아짐
profile
기록하는 블로그

2개의 댓글

comment-user-thumbnail
3일 전

데구리님 for 문 안에는 switch 안쓰는게 좋긴해여.

왜냐구요?

1개의 답글