洛谷P1449 后缀表达式

https://www.luogu.com.cn/problem/P1449

题目描述

所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级)。

如:3*(5–2)+7对应的后缀表达式为:3.5.2.-*7.+@。’@’为表达式的结束符号。‘.’为操作数的结束符号。

输入格式

输入:后缀表达式

输出格式

输出:表达式的值

输入输出样例

输入 #1复制

3.5.2.-*7.+@

输出 #1复制

16

说明/提示

字符串长度,1000内。

这道题是用栈进行实现,有一点需要注意:栈顶的操作数为operator2,栈顶的数弹出后的那个栈顶的操作数为operator1,进行运算时是 operator1 = operato1r operation operator2

代码:

#include <bits/stdc++.h>
#define MAXN 2000005
#define ll long long
ll n,m;
using namespace std;
stack<int> st;
int main()
{
    string str;
    cin>>str;
    char opt;
    int x,y;
    int len,num,j;
    len=str.length();
    for(int i=0; i<len; i++)
    {
        if(str[i]=='@')
        {
            break;
        }
        if(str[i]=='.')
        {
            continue;
        }
        if(str[i]>='0'&&str[i]<='9')
        {
            num=0;
            j=i;
            for(j; j<len; j++)
            {
                if(str[j]>='0'&&str[i]<='9')
                {
                    num = num*10 + str[j]-'0';
                }else
                {
                    break;
                }
            }
            st.push(num);
//cout<<num<<endl;
            i=j-1;
            continue;
        }else
        {
            opt = str[i];
            x = st.top();st.pop();
            y = st.top();st.pop();
      //      cout<<y<<" "<<x<<" "<<opt<<endl;
            if(opt=='+')
            {
                y = y+x;
            }else if(opt=='-')
            {
                y = y-x;
            }else if(opt == '*')
            {
                y = y*x;
            }else
            {
                y = y/x;
            }
            st.push(y);
        }
    }
    cout<<st.top()<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九久呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值