1. 用一个变量存储二元操作符计算的结果,每次计算完都要放会栈;
  2. 比较麻烦的另一个点就是字符串和数字的转换:
  • to_string(int val); //具体可以在网上找到原型。
  • atoi(str.c_str); //字符串转换成整数。
class Solution {
public:
    /**
     * 
     * @param tokens string字符串vector 
     * @return int整型
     */
    int evalRPN(vector<string>& tokens) {
        // write code here
        stack<string> st;
        int len = tokens.size();
        int ans = 0;
        //将字符串转换成数字->有没有现成的函数?
        for(int i = 0; i < len; i++) {
            if(tokens[i] == "+") {
                int num2 = atoi(st.top().c_str());
                st.pop();
                int num1 = atoi(st.top().c_str());
                st.pop();
                ans = num1 + num2;
                st.push(to_string(ans));
            }else if(tokens[i] == "-") {
                int num2 = atoi(st.top().c_str());
                st.pop();
                int num1 = atoi(st.top().c_str());
                st.pop();
                ans = num1 - num2;
                st.push(to_string(ans));
            }else if(tokens[i] == "*") {
                int num2 = atoi(st.top().c_str());
                st.pop();
                int num1 = atoi(st.top().c_str());
                st.pop();
                ans = num1 * num2;
                st.push(to_string(ans));
            }else if(tokens[i] == "/") {
                int num2 = atoi(st.top().c_str());
                st.pop();
                int num1 = atoi(st.top().c_str());
                st.pop();
                ans = num1 / num2;
                st.push(to_string(ans));
            }else {
                st.push(tokens[i]);
            }
        }
        ans = atoi(st.top().c_str());
        st.pop();
        return ans;
    }
};