leetcode150———逆波兰表达式求值

//逆波兰表达式求值
#include
#include
#include
using namespace std;
string postexp;
double GetValue()
{
    stack opand;
    double a, b, c, d;
    char ch;
    int i = 0;
    while (i < postexp.length())
    {
        ch = postexp[i];
        switch (ch)
        {
        case '+':
            a = opand.top();
            opand.pop();
            b = opand.top();
            opand.pop();
            c = a + b;
            opand.push(c);
            break;
        case '-':
            a = opand.top();
            opand.pop();
            b = opand.top();
            opand.pop();
            c = b - a;
            opand.push(c);
            break;
        case '*':
            a= opand.top();
            opand.pop();
            b = opand.top();
            opand.pop();
            c = b * a;
            opand.push(c);
            break;
        case '/':
            a = opand.top();
            opand.pop();
            b = opand.top();
            opand.pop();
            c = b / a;
            opand.push(c);
            break;
        default://数字字符
            //连续数字字符的情况
            d = 0;
            while (ch >= '0' && ch <= '9')
            {
                d = d * 10 + (ch - '0');
                i++;
                ch = postexp[i];
            }
            opand.push(d);
            break;

        }
        i++;
    }
    return opand.top();
}
int main()
{
    string exp;
    getline(cin, exp);
    postexp = exp;
    cout << GetValue() << endl;
    return 0;
}

你可能感兴趣的:(c++,算法,开发语言)