当前位置: 移动技术网 > IT编程>开发语言>C/C++ > 【题解】洛谷 P1449 后缀表达式

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

2019年10月07日  | 移动技术网IT编程  | 我要评论

平谷轻轨,澳元走势,妖精的独步舞

目录


题目

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;
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网