多项式运算(渣算法)

#include <cstdio>
#include <string>
#include <string.h>
int num[100];
int pointnum=-1;
void push(int);
int popn(bool);
bool isNullnum();

int chr[100];
int pointchr=-1;
void push(char);
char popc(bool);
bool isNullchr();

char str[256];

void algo();

int main()
{
    bool HaveNum=false;
    memset(str,0,sizeof(str));
    scanf("%s",str);
    str[strlen(str)]=')';
    push('(');
    int temp=0;
    for(int i=0;i<strlen(str);i++)
    {
        if(str[i]>='0' && str[i]<='9')
        {
            HaveNum=true;
            temp*=10;
            temp+=str[i]-48;
        }
        else
        {
            char chr=str[i];
            if(HaveNum==true)
            {
                push(temp);
                HaveNum=false;
                temp=0;
            }

            switch(chr)
            {
            case '+':
                while(popc(false)!='(' && !isNullchr()) algo();
                push(chr);
                break;
            case '-':
                while(popc(false)!='(' && !isNullchr()) algo();
                push(chr);
                break;
            case '*':
                while(popc(false)!='(' && popc(false)!='+' && popc(false)!='-' && !isNullchr()) algo();
                push(chr);
                break;
            case '/':
                while(popc(false)!='(' && popc(false)!='+' && popc(false)!='-' && !isNullchr()) algo();
                push(chr);
                break;
            case '(':
                push(chr);
                break;
            case ')':
                while(popc(false)!='(')
                {
                    algo();
                }
                if(popc(false)=='(')
                    chr=popc(true);
                break;
            }
        }
    }
    while(!isNullchr())
    {
        algo();
    }
    printf("%d\n",popn(false));
    return 0;
}

void push(int i)
{
    num[++pointnum]=i;
}
void push(char i)
{
    chr[++pointchr]=i;
}
int popn(bool i)
{
    if(i==true)
        return num[pointnum--];
    else
        return num[pointnum];
}
char popc(bool i)
{
    if(i==true)
        return chr[pointchr--];
    else
        return chr[pointchr];
}
bool isNullchr()
{
    if(pointchr!=-1)
        return false;
    else
        return true;
}
bool isNullnum()
{
    if(pointnum!=-1)
        return false;
    else
        return true;
}
void algo()
{
    int b=popn(true);
    int a=popn(true);
    char chr=popc(true);
    switch(chr)
    {
    case '+':
        push(a+b);
        break;
    case '-':
        push(a-b);
        break;
    case'*':
        push(a*b);
        break;
    case '/':
        push(a/b);
        break;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值