solution.cpp 857 字节
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#include <iostream>
using namespace std;

struct EV
{
    int result; //计算结果
    int n;      //消耗掉的字符数
};

struct EV evaluate(char *x)
{
    struct EV ev = {0, 0};
    struct EV v1;
    struct EV v2;

    if (*x == 0)
        return ev;

    if (x[0] >= '0' && x[0] <= '9')
    {
        ev.result = x[0] - '0'; //字符转数字
        ev.n = 1;
        return ev;
    }

    v1 = evaluate(x + 1);
    v2 = evaluate(x + v1.n + 1);

    if (x[0] == '+')
        ev.result = v1.result + v2.result;
    if (x[0] == '*')
        ev.result = v1.result * v2.result;
    if (x[0] == '-')
        ev.result = v1.result - v2.result;
    ev.n = 1 + v1.n + v2.n;

    return ev;
}

int main(int argc, char **argv)
{
    string str = "-+3*5+261";
    const EV &ev = evaluate((char *)(str.c_str()));
    cout << ev.result << endl;
    return 0;
}