10700 无括号的表达式

本文介绍了一种使用栈实现表达式求值的算法,该算法能够处理加法和乘法混合运算,并通过调整运算符优先级来计算最大值和最小值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <stack>
#include <cmath>
#define M 500

using namespace std;

long long deal(char *str,char a,char b)
{
    stack<char>operat;
    stack<long long>num;

    long long len = strlen(str);
    long long flage = 0;
    long long n;
    char ope;
    for(long long i = 0;i < len;i++)
    {
        if(!flage){
            sscanf(&str[i],"%lld",&n);
            num.push(n);
            if(n >= 10) i++;
            flage = 1;
        }
        else{
            ope = str[i];
            flage = 0;

            if(!operat.empty())
            {
                char cal = operat.top();
                long long x,y;
                if(ope == b || cal == a){
                   operat.pop();
                   x = num.top();num.pop();
                   y = num.top();num.pop();
                   long long r;
                   if(cal == '*')
                     r = x * y;
                   else r = x + y;

                   num.push(r);
                }

                operat.push(ope);
            }
            else operat.push(ope);
        }
    }

    while(!operat.empty())
    {
        char cal = operat.top();
        operat.pop();
        long long x,y;
        x = num.top(); num.pop();
        y = num.top(); num.pop();
        long long r;
        if(cal == '*')
            r = x * y;
        else r = x + y;

        num.push(r);
    }

    return num.top();
}

int main()
{
    //freopen("in.in","r",stdin);

    long long T;
    long long minv,maxv;
    char str[M];
    scanf("%lld",&T); getchar();
    while(T--)
    {
        gets(str);
        minv = deal(str,'*','+');
        maxv = deal(str,'+','*');

    printf("The maximum and minimum are %lld and %lld.\n",maxv,minv);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值