首页 > 其他 > 详细

【题解】洛谷 P1449 后缀表达式

时间:2019-10-07 15:07:06      阅读:67      评论:0      收藏:0      [点我收藏+]

题目

P1449 后缀表达式

思路

栈。题目说的不是很清楚,没说包含什么操作。除法用整数除法就行。
先string读入字符串,然后从前往后看如果是个数字就入栈,如果是运算符就从栈里弹出两个数计算再入栈。

$Code$

#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<stack>
#include<algorithm>
std::string sss;
std::stack<int> s1;

inline void read(int &T) {
    int x=0;bool f=0;char c=getchar();
    while(c<'0'||c>'9'){if(c=='-')f=!f;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    T=f?-x:x;
}

int main() {
    std::cin>>sss;
    int len=sss.length();
    int sum=0;
    for(int i=0;i<len-1;++i) {
        if(sss[i]>='0'&&sss[i]<='9') {
            sum=sum*10+sss[i]-'0';
        }else {
            if(sss[i]=='.') {
                s1.push(sum);
                sum=0;
            }
            else {
                int x1=s1.top();
                s1.pop();
                int x2=s1.top();
                s1.pop();
                if(sss[i]=='+') s1.push(x1+x2);
                if(sss[i]=='-') s1.push(x2-x1);
                if(sss[i]=='*') s1.push(x2*x1);
                if(sss[i]=='/') s1.push(x2/x1);
            }
        }
    }
    std::cout<<s1.top();
    return 0;
}

【题解】洛谷 P1449 后缀表达式

原文:https://www.cnblogs.com/poi-bolg-poi/p/11630353.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!