您的位置:首页 > 编程语言 > Lua

evaluate-reverse-polish-notation

2016-07-17 18:03 399 查看


题目描述

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();

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息