链接:https://ac.nowcoder.com/acm/problem/212914
来源:牛客网

给定一个后缀表达式s,计算它的结果,例如,1+1对应的后缀表达式为1#1#+,‘#’作为操作数的结束符号。
其中,表达式中只含有‘+’、’-‘、’*‘三种运算,不包含除法。
本题保证表达式一定合法,且计算过程和计算结果的绝对值一定不会超过10^{18}10
18

示例1
输入
"1#1#+"
返回值
2
说明
1#1#+这个后缀表达式表示的式子是1+1,结果为2
示例2
输入
"12#3#+15#*"
返回值
225
说明
12#3#+15#这个后缀表达式表示的式子是(12+3)15,结果为225

解:题目本身很简单,用一个栈堆入数字,遇到运算符就把数字从栈里拿出来,但是本题要用class一个方法才能过题,而题目本身并未指出,我被恶心到了。

class Solution {
public:
stack <long long> st;    
long long solve(string str)
{
    long long d = 0;
    int i=0;
    int n=str.length();
    while (i<n)
    {
        long long x, y;
        if (str[i] <= '9' && str[i] >= '0')
        {
            d = str[i]-(long long)'0' + d * 10;        
        }
        else if (str[i] == '#') {
            st.push(d);
            d = 0;
            i++;
            continue;
        }
        else if (str[i] == '*')
        {
            y = st.top();
            st.pop();
            x = st.top();
            st.pop();
            st.push(x * y);
        }
        else if (str[i] == '/')
        {
            y = st.top();
            st.pop();
            x = st.top();
            st.pop();
            st.push(x / y);
        }
        else if (str[i] == '+')
        {
            y = st.top();
            st.pop();
            x = st.top();
            st.pop();
            st.push(x + y);
        }
        else if (str[i] == '-')
        {
            y = st.top();
            st.pop();
            x = st.top();
            st.pop();
            st.push(x - y);
        }     
        i++;
    }
    return st.top();
}
};