poj 1539 Evaluating Simple C Expressions

虽然划分在数据结构里,但感觉什么都没用到。

简单的字符串处理罢了。

 最后计算的时候把++,--都去掉。

用一个数组a[27]保存字母的值。

easy

#include <iostream>
#include <cstdio>
#include <fstream>
#include <cstring>
#include <string.h>
#include <stack>
using namespace std;
void strip(char *p){
    int cnt=0;
    char *temp=p;
    char new_char[100];
    while(*p){
        if(*p!=' '){new_char[cnt++]=*p;}
        p++;
    }
    strcpy(temp+2,new_char);
    temp[cnt+2]='!';temp[cnt+3]='!';
    temp[cnt+4]='\0';
    temp[0]='!';temp[1]='!';
}
int calculate(char *p){
    int num=0,add;
    while(*p){
        if(*p>='a'&&*p<='z')
        {
            add = *p-'a'+1;
            if(*(p-1)=='-')
            {
                add=-add;
            }
            num+=add;
        }
        p++;
    }
    return num;
}
void function(char *p){
    bool flag[30];
    int num[30],cnt=1;
    char calcu[100],s;
    memset(flag,0,sizeof(flag));
    while(*p){
        if(*p>='a'&&*p<='z')
        {
            flag[*p-'a'+1]=1;
            num[*p-'a'+1]=*p-'a'+1;
            if(*(p-1)=='+'&&*(p-2)=='+')
            {
                calcu[cnt++]=*p+1;
                num[*p-'a'+1]+=1;
            }
            else if(*(p-1)=='-'&&*(p-2)=='-')
            {
                calcu[cnt++]=*p-1;
                num[*p-'a'+1]-=1;
            }
            else if(*(p+1)=='+'&&*(p+2)=='+')
            {
                calcu[cnt++]=*p;
                num[*p-'a'+1]+=1;
            }
            else if(*(p+1)=='-'&&*(p+2)=='-')
            {
                calcu[cnt++]=*p;
                num[*p-'a'+1]-=1;
            }
            else{
                calcu[cnt++]=*p;
            }
        }
        else if(*p=='+')
        {
            if(*(p-1)!='+'&&*(p+1)!='+')
            {
                calcu[cnt++]=*p;
            }
        }
        else if(*p=='-')
        {
            if(*(p-1)!='-'&&*(p+1)!='-')
            {
                calcu[cnt++]=*p;
            }
        }
        p++;
    }
    calcu[cnt]='\0';
    calcu[0]='+';
    cout<<"    value = "<<calculate(calcu)<<endl;
    for(int i=0;i<30;i++)
    {
        if(flag[i]){
            s='a'+i-1;
            cout<<"    "<<s<<" = "<<num[i]<<endl;
            }
    }
}
int main()
{
    //ifstream cin("ha.txt");
    char senten[100];
    while(cin.getline(senten,100)&&strlen(senten))
    {
        cout<<"Expression: "<<senten<<endl;
        strip(senten);
        //cout<<senten<<endl;
        function(senten);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值