栈:Emacs计算器

Emacs号称神的编辑器,它自带了一个计算器。与其他计算器不同,它是基于后缀表达式的,即运算符在操作数的后面。例如“2 3+”等价于中缀表达式的“2 + 3”。
请你实现一个后缀表达式的计算器。

输入描述:
输入包含多组数据。

每组数据包括两行:第一行是一个正整数n (3≤n≤50);紧接着第二行包含n个由数值和运算符组成的列表。

“+-*/”分别为加减乘除四则运算,其中除法为整除,即“5/3=1”。


输出描述:
对应每一组数据,输出它们的运算结果。
示例1

输入

3
2 3 +
5
2 2 + 3 *
5
2 2 3 + *

输出

5
12
10

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<cstdlib>
#include<string>
#include<stack>
#include<sstream>
using namespace std;
 
int f(string x)
{
    stringstream ss;
    ss<<x;
    int num;
    ss>>num;
    return num;
}
int main()
{
 
    int n;
    while(cin>>n)
    {
        stack<int>s;
        for(int i=0; i<n; i++)
        {
            string x;
            cin>>x;
            if(x=="+")
            {
                int a,b;
                a=s.top();
                s.pop();
                b=s.top();
                s.pop();
                a+=b;
                s.push(a);
            }
            else if(x=="+")
            {
                int a,b;
                a=s.top();
                s.pop();
                b=s.top();
                s.pop();
                a+=b;
                s.push(a);
            }
            else if(x=="-")
            {
                int a,b;
                a=s.top();
                s.pop();
                b=s.top();
                s.pop();
                a=b-a;
                s.push(a);
            }
            else if(x=="*")
            {
                int a,b;
                a=s.top();
                s.pop();
                b=s.top();
                s.pop();
                a*=b;
                s.push(a);
            }
            else if(x=="/")
            {
                int a,b;
                a=s.top();
                s.pop();
                b=s.top();
                s.pop();
                a=b/a;
                s.push(a);
            }
            else
            {
                int a=f(x);
                s.push(a);
            }
        }
        cout<<s.top()<<endl;
    }
 
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值