LeetCode | 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

题目解析:

//被除数为0
//有负数的情况
class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        if(tokens.size() == 0)
            return 0;
        stack<int> integer;
        for(int i = 0;i < tokens.size();i++){
            if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "/" || tokens[i] == "*"){
                int b = integer.top();
                integer.pop();
                int a = integer.top();
                integer.pop();
                if(tokens[i] == "+")
                    integer.push(a+b);
                else if(tokens[i] == "-")
                    integer.push(a-b);
                else if(tokens[i] == "/"){
                    if(b == 0)
                        return 0;
                    integer.push(a/b);
                }

                else
                    integer.push(a*b);
            }else{
                int num = StrToNum(tokens[i]);
                integer.push(num);
            }
        }
        return integer.top();
    }

    int StrToNum(string s){
        int len = s.size();
        int num = 0;
        if(s[0] == '-'){
            for(int i = 1;i < len;i++)
                num = num*10 + (s[i]-'0');
            return 0-num;
        }
        for(int i = 0;i < len;i++)
            num = num*10 + (s[i]-'0');
        return num;
    }
};

字符串转化为数字,可以利用系统函数stoi(s)。

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        if(tokens.size() == 0)
            return 0;
        stack<int> integer;
        for(int i = 0;i < tokens.size();i++){
            if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "/" || tokens[i] == "*"){
                int b = integer.top();
                integer.pop();
                int a = integer.top();
                integer.pop();
                if(tokens[i] == "+")
                    integer.push(a+b);
                else if(tokens[i] == "-")
                    integer.push(a-b);
                else if(tokens[i] == "/")
                    integer.push(a/b);
                else
                    integer.push(a*b);
            }else{
                integer.push(stoi(tokens[i]));
            }
        }
        return integer.top();
    }
};



点赞