엔지니어 게시판
LeetCode 솔루션 분류

[12/17] 150. Evaluate Reverse Polish Notation

컨텐츠 정보

본문

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*, and /. Each operand may be an integer or another expression.

Note that division between two integers should truncate toward zero.

It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.

 

Example 1:

Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3:

Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

 

Constraints:

  • 1 <= tokens.length <= 104
  • tokens[i] is either an operator: <code style="border: 1px solid rgba(247, 250, 255, 0.12); box-sizing: border-box; --tw-border-spacing-x:0; --tw-border-spacing-y:0; --tw-translate-x:0; --tw-translate-y:0; --tw-rotate:0; --tw-skew-x:0; --tw-skew-y:0; --tw-scale-x:1; --tw-scale-y:1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strict

관련자료

댓글 1

학부유학생님의 댓글

  • 익명
  • 작성일
class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        operators = "/*+-"

        def calc(op):
            num2 = stack.pop()
            num1 = stack.pop()
            if op == '+':
                stack.append(num1+num2)
            elif op == '-':
                stack.append(num1-num2)
            elif op == '*':
                stack.append(num1*num2)
            elif op == '/':
                stack.append(int(num1/num2))
        
        for string in tokens:
            if string[0].isdigit():
                stack.append(int(string))

            elif string in operators:
                calc(string)
            
            elif string[0] == "-":
                stack.append(-int(string[1:]))
                    
        return stack[-1]
전체 396 / 2 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 201 명
  • 오늘 방문자 2,917 명
  • 어제 방문자 6,462 명
  • 최대 방문자 11,134 명
  • 전체 회원수 1,050 명
알림 0