P1449 suffix expression (Luogu)

Original title portal

Insert picture description here
Idea: Define a stack to store the int type, and then convert the input data and store it in the stack, but divide it by arithmetic symbols, advance the first number, then enter the second number, and then throw the last number first At this time, the advanced number is the top element of the stack, and then after the two numbers are calculated, the first number is thrown out and the operation result sum is pushed onto the stack, which can be looped.

Code reference

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1001;
char a[MAXN];
int sum,k;
stack <int> stk;
int main(){
    
    
    gets(a);
	for(int i=0;a[i]!='@';i++)
	{
    
    
		if(a[i]=='.')
		{
    
    
			sum=0,k=1;
			//将数据转换后存入栈中
			for(int j=i-1;j>=0&&a[j]>='0'&&a[j]<='9';j--){
    
    
                sum=sum+(a[j]-'0')*k;
                k*=10;
			}
			stk.push(sum);
			continue;
		}
		if(a[i]>='0' && a[i]<='9')
            continue;
		sum=stk.top();//栈顶元素
		stk.pop();//弹出栈顶元素
		if(a[i]=='+') sum=stk.top()+sum;
		if(a[i]=='-') sum=stk.top()-sum;
		if(a[i]=='*') sum=stk.top()*sum;
		if(a[i]=='/') sum=stk.top()/sum;
		stk.pop();
		stk.push(sum);//将sum压入栈中
    }
	cout<<sum<<endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/Bertil/article/details/106794212