华为OD机试-仿LISP运算

// Online C++ compiler to run C++ program online
#include<iostream>
#include<vector>
#include<stdlib.h>
#include<algorithm>
#include<iomanip>
#include<string.h>
#include<exception> 
#include<map>
#include<cmath>
#include<unordered_map>
#include<set>
#include<climits>
#include<ctype.h>
#include<queue>
#include<stack>
#include<string>
#include<vector>
using namespace std;

#define TYPE_OP 1
#define TYPE_VAL 2
struct Word
{
    Word(int _type, string _token)
    {
        type = _type;
        token = _token;
    }

    int type = 0;
    string token;
};

void scan(string str, list<Word>& opList) {
    for (uint32_t i = 0; i < str.size(); ) {
        for (; (str[i] == ' ' || str[i] == '\t'); ++i) continue;

        if (str[i] == '(' || str[i] == ')') {
            ++i;
            continue;
        }

        for (; (str[i] == ' ' || str[i] == '\t'); ++i) continue;

        char ch[128] = { 0 };
        int k = 0;
        for ( ; str[i] >= 'a' && str[i] <= 'w'; k++, i++) {
            ch[k] = str[i];
        }
        ch[k] = '\0';
        opList.push_back(Word(TYPE_OP, string(ch)));

        for (; (str[i] == ' ' || str[i] == '\t'); ++i) continue;

        if (str[i] == '(') {
            ++i;
            continue;
        }

        k = 0;
        for (; (str[i] >= '0' && str[i] <= '9') || (str[i] == '-'); k++, i++) {
            ch[k] = str[i];
        }
        ch[k] = '\0';
        opList.push_back(Word(TYPE_VAL, string(ch)));

        for (; (str[i] == ' ' || str[i] == '\t'); ++i) continue;

        k = 0;
        for (; (str[i] >= '0' && str[i] <= '9') || (str[i] == '-'); k++, i++) {
            ch[k] = str[i];
        }
        ch[k] = '\0';
        opList.push_back(Word(TYPE_VAL, string(ch)));
    }
}

int cal(list<Word>& opList) {
    int val = 0;

    Word op = opList.front();
    opList.pop_front();

    int a, b;
    if (opList.front().type == TYPE_OP)
    {
        a = cal(opList);
    }
    else
    {
        a = atoi(opList.front().token.c_str());
        opList.pop_front();
    }

    if (opList.front().type == TYPE_OP)
    {
        b = cal(opList);
    }
    else
    {
        b = atoi(opList.front().token.c_str());
        opList.pop_front();
    }

    if (op.token == "add") {
        val = a + b;
    }
    else if (op.token == "sub") {
        val = a - b;
    }
    else if (op.token == "mul") {
        val = a * b;
    }
    else {
        if (b == 0) {
            cout << "error" << endl;
            exit(0);
        }
        val = a / b;
    }

    return val;
}

int main() {
    string str;
    list<Word> opList;
    getline(cin, str);

    scan(str, opList);

    int val = cal(opList);

    cout << val << endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值