[Leetcode 150] Evaluate Reverse Polish Notation

이재윤·2025년 2월 11일
0

https://leetcode.com/problems/evaluate-reverse-polish-notation/description/

1) 코드

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        
        stk = [] 

        for c in tokens:
            if c == '+':
                stk.append(stk.pop()+stk.pop())
            elif c == '-':
                second, first = stk.pop(), stk.pop()
                stk.append(first-second)
            elif c == '*':
                stk.append(stk.pop()*stk.pop())
            elif c == '/':
                second, first = stk.pop(), stk.pop()
                stk.append(int(first / second))
            else:
                stk.append(int(c))

        return stk[0]

2) 해설

  • Postfix 방식의 연산으로 stack을 통해서 문제를 해결할 수 있다
    -> 음수일 때, 어떻게 계산하는지 잘 알아두도록 하자

0개의 댓글