问题 D: 数据结构基础4-计算

题目描述

小明在你的帮助下,破密了Ferrari设的密码门,正要往前走,突然又出现了一个密码门,门上有一个算式,其中只有“(”,“)”,“0-9”,“+”,“-”,“*”,“/”,“^”求出的值就是密码。小明数学学得不好,还需你帮他的忙。(“/”用整数除法)

输入

输入文件calc.in共1行,为一个算式。

输出

输出文件calc.out共1行,就是密码。

样例输入 Copy
1+(3+2)*(7^2+6*9)/(2) 
样例输出 Copy
258 
提示

100%的数据满足:算式长度<=30 其中所有数据在231-1的范围内。

#include<cctype>
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<stack>
using namespace std;
stack<int> values;
stack<char> operators;
int priority(char ch)
{
    int res = 0;
    switch (ch)
    {
        case '+':
        case '-':
            res = 1;
            break;
        case'*':
        case'/':
            res = 2;
            break;
        case'^':
            res = 3;
            break;
    }
    return res;
}
void calculate()
{
    int x = 0, y = 0, result = 0;
    y = values.top();
    values.pop();
    x = values.top();
    values.pop();
    char ch;
    ch = operators.top();
    operators.pop();
    switch (ch)
    {
        case '+':
            result = x + y;
            break;
        case '-':
            result = x - y;
            break;
        case '*':
            result = x * y;
            break;
        case '/':
            result = x / y;
            break;
        case '^':
            result = pow(x, y);
            break;
    }
    values.push(result);
}
int main()
{
    int has_num = 0;
    int value = 0;
    char ch;
    string s;
    cin >> s;
    int lenth = s.length();
    for (int i = 0; i < lenth; i++)
    {
        ch = s[i];
        if (isdigit(ch))
        {
            value = value * 10 + ch - '0';
            has_num = 1;
        }
        else
        {
            if (has_num)
            {
                values.push(value);
                has_num = 0;
                value = 0;
            }
            if (ch == '(')
            {
                operators.push(ch);
                continue;
            }
            if (ch == ')')
            {
                while (operators.top() != '(')
                {
                    calculate();
                }
                operators.pop();
                continue;
            }
            if (operators.empty())
            {
                operators.push(ch);
            }
            else
            {
                while (!operators.empty() && priority(operators.top()) >= priority(ch))
                {
                    calculate();
                }
                operators.push(ch);
            }
        }
    }
    if (has_num)
    {
        values.push(value);
    }
    while (!operators.empty())
    {
        calculate();
    }
    cout << values.top() << endl;
    return 0;
}
 

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值