算法题:前缀表达式的运算

输入描写叙述:

输入包括多组数据,每组数据包括两行。

第一行为正整数n(3≤n≤50)。紧接着第二行包括n个由数值和运算符组成的列表。

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

输出描写叙述:

相应每一组数据,输出它们的运算结果。

输入样例:

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

输出样例:

5
12
10

#include <iostream>
#include <string.h>
#include <stack>
using namespace std;


bool Is_Op(char ch)
{
    return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
}
int Deal(int a, char op, int b)
{
    switch (op)
    {
    case '+':
        return a + b;
        break;
    case '-':
        return a - b;
        break;
    case '*':
        return a*b;
        break;
    case '/':
        if (b!=0)
        return a / b;
        break;
    default:
        break;
    }
}
int main()

{
    int n;
    stack<string> NUM;
    while (cin >> n)
    {
        char *inputStr = new char[n];
        cin.get();
        cin.get(inputStr,n*2);
        string inputSTR(inputStr);
        string SStr(inputSTR.rbegin(),inputSTR.rend());
        strcpy(inputStr,SStr.c_str());
        char *p = inputStr;
        while (*p != '\0' || NUM.size()!=1)
        {
            string s;
            if (*p == ' ')
            {
                p++;
                continue;
            }
            if (Is_Op(*p))
            {
                string num1 = NUM.top();
                NUM.pop();
                string NUM1(num1.rbegin(), num1.rend());
                string num2 = NUM.top();
                string NUM2(num2.rbegin(), num2.rend());
                NUM.pop();
                int result = Deal(atoi(NUM1.c_str()),*p,atoi(NUM2.c_str()));
                char *buff = new char[50];
                sprintf(buff,"%d",result);
                NUM.push(buff);
                p++;
            }
            else
            {
                while (*p != ' ' && *p != '\0')
                {
                    s += *p;
                    p++;
                }
                NUM.push(s);        
            }
        }
        cout<<NUM.top().c_str() << endl;
        NUM.pop();
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值