这道题不用考虑操作数是负数的情况?

P1449 后缀表达式

yubing_lml @ 2019-08-20 10:39:09

如题。。一开始想复杂了,把负数也搞进去,代码如下,有点问题所以WA了3个点。。

#include<iostream>
#include<stack>
#include<string>
using namespace std;

int main()
{
    stack<int> number;
    int tmp, num1, num2;
    string str;
    cin >> str;
    for (int i = 0; str[i] != '@'; i++)
    {
        if (str[i] == '.')
        {
            tmp = 0;
            int j = i - 1,c=1;
            while (j >= 0 && (str[j] >= '0'&&str[j] <= '9'))
            {
                tmp += (str[j] - '0')*c;
                c *= 10;
                j--;
            }
            if (j >= 0 && str[j] == '-'&&number.size() < 2)
                tmp *= -1;
            number.push(tmp);
        }
        else if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/')
        {
            if (str[i] == '-'&&number.size() < 2)
                continue;
            num1 = number.top();
            number.pop();
            num2 = number.top();
            number.pop();
            if (str[i] == '+')
                number.push(num2 + num1);
            else if (str[i] == '-')
                number.push(num2 - num1);
            else if (str[i] == '*')
                number.push(num2*num1);
            else
                number.push(num2 / num1);
        }
    }
    cout << number.top();
    cin >> str;
    return 0;
}

后来把负数判定去了,就AC了


by SJC_03 @ 2019-08-20 10:42:08

......

您或许可以去写题解


|