ACM 训练日志记录 · 思考 · 成长 提交 / 修改记录
王梓豪 / 题目列表训练档案
导出

P1449 后缀表达式

来源:洛谷 ★ 1000

本题活力0.31按难度、完成结果与训练证据估算

算法如山行则将至

题目描述

计算后缀表达式的值,按顺序处理运算符,除法向0取整。

代码

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s;
    cin>>s;
    stack<int> st;
    int num = 0;
    for (char c : s)
    {
        if (c>='0'&&c<= '9')
        {
            num = num*10+(c-'0');
        }
        else if (c=='.')
        {
            st.push(num);
            num=0;
        }
        else if (c=='+'||c =='-'||c =='*'||c =='/')
        {
            int b = st.top(); st.pop();
            int a = st.top(); st.pop();
            int res;
            if (c == '+') res = a + b;
            else if (c == '-') res = a - b;
            else if (c == '*') res = a * b;
            else res = a / b;
            st.push(res);
        }
        else if (c == '@')
        {
            break;
        }
    }
    cout << st.top() << endl;
    return 0;
}