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 str2int(string token){
        int num=0;
        int start=0;
        int isNev = 1;
        //判断符号
        if(token[0]=='-'){isNev=-1; start++;}
        else if(token[0]=='+')start++;
        for(int i=start; i<token.length(); i++){
            num=10*num+(token[i]-'0');
        }
        return num*isNev;
    }
    
    bool isOp(string token){
        if(token=="/" || token=="+" || token=="-" || token=="*")
            return true;
    }
    
    int evalRPN(vector<string> &tokens) {
        stack<int> st;
        for(int i=0; i<tokens.size(); i++){
            if(isOp(tokens[i])){
                //如果是运算符,则计算栈顶元素,然后将结果入栈
                int val1 = st.top(); st.pop();
                int val2 = st.top(); st.pop();
                int res = 0;
                if(tokens[i]=="+")  res = val2 + val1;
                else if(tokens[i]=="-")  res = val2 - val1;
                else if(tokens[i]=="*")  res = val2 * val1;
                else if(tokens[i]=="/")  res = val2 / val1;
                //计算结果入栈
                st.push(res);
            }
            else{
                //数字入栈
                st.push(str2int(tokens[i]));
            }
        }
        return st.top();
    }
};LeetCode: Evaluate Reverse Polish Notation [150],布布扣,bubuko.com
LeetCode: Evaluate Reverse Polish Notation [150]
原文:http://blog.csdn.net/harryhuang1990/article/details/36204735