[Daily question] 29: Inverse Polish expression evaluation

Title description

According to the reverse Polish notation , find the value of the expression.

Valid operators include +,-, *, /. Each operand can be an integer or another inverse Polish expression.

Description:

Integer division retains only the integer part.
Given an inverse Polish expression is always valid. In other words, the expression always results in a valid value and there is no divisor of 0.

Example 1:

输入: ["2", "1", "+", "3", "*"]
输出: 9
解释: ((2 + 1) * 3) = 9

Example 2:

输入: ["4", "13", "5", "/", "+"]
输出: 6
解释: (4 + (13 / 5)) = 6

Example 3:

输入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
输出: 22
解释: 
  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

Answer code

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> m_data;

        for(auto & i : tokens){
            //当i为数字时入栈(需要检测负数)
            //int atoi (const char * str);
            //atoi (表示 ascii to integer)是把字符串转换成整型数的一个函数(C语言库函数)
            //c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同. 
            //这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string对象转换成c中的字符串样式。
            if(i[1] || isdigit(i[0])){
                m_data.push(atoi(i.c_str()));
            }
            else{
                int num2 = m_data.top();
                m_data.pop();
                int num1 = m_data.top();

                switch(i[0])
                {
                case '+':
                    m_data.top() = num1+num2;
                    break;
                case '-':
                    m_data.top() = num1-num2;
                    break;
                case '*':
                    m_data.top() = num1*num2;
                    break;
                case '/':
                    m_data.top() = num1/num2;
                    break;
                }
            }
        }
        return m_data.top();
    }
};
Published 152 original articles · praised 45 · 10,000+ views

Guess you like

Origin blog.csdn.net/AngelDg/article/details/105380086