0
点赞
收藏
分享

微信扫一扫

evaluate-reverse-polish-notation


题目描述


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

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

Some examples:



["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6


class Solution {

 public:

     int evalRPN(vector<string>& tokens) {

        stack<int> stack;

          

         for (int i = 0; i < tokens.size(); ++i) {

               if (tokens[i] == "+") {

                 int a = stack.top();

                   stack.pop();

                 int b = stack.top();

                   stack.pop();

                 stack.push(a + b);

             } else if (tokens.at(i) == "-") {

                 int a = stack.top();

                 stack.pop();

                 int b = stack.top(); 

                 stack.pop();

                 stack.push(b - a);

             } else if (tokens.at(i) == "*") {

                 int a = stack.top();

                 stack.pop();

                 int b = stack.top();

                 stack.pop();

                 stack.push(a * b);

             } else if (tokens.at(i) == "/") {

                 int a = stack.top();

                 stack.pop();

                 int b = stack.top();

                 stack.pop();

                 stack.push(b / a);

             } else {

                 //进行将string类型转换为int 类型

                 stack.push(stoi(tokens[i]));

             }

         }

         return stack.top();

     }

 };

举报

相关推荐

0 条评论