样例通过+1AC+3WA+2RE,蒟蒻请求大佬支援

P1449 后缀表达式

伏地魔老杨 @ 2022-08-27 10:00:34

#include <iostream>
#include <stack>
#include <string>
using namespace std;
stack<long long> st;
string s;
int main()
{
    long long sum = 0;
    cin >> s;
    for (int i = 0; i < s.size(); i++)
    {
        long long a, b;
        if (s[i] == '.') continue;
        if (s[i] == '@')
        {
            cout << st.top();
            return 0;
        }
        if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/')
        {
            a = st.top();
            st.pop();
            b = st.top();
            st.pop();
            if (s[i] == '+') st.push(a + b);
            if (s[i] == '-') st.push(b - a);
            if (s[i] == '*') st.push(a * b);
            if (s[i] == '/') st.push(b / a);
            continue;
        }
        st.push(s[i] - '0');
    }
}

by LeTu_Jun @ 2022-08-27 10:03:41

st.push(s[i] - '0'); 这一句前面是不是应该有 else


by Cx_A_Yj @ 2022-08-27 11:24:40

@LeTu_Jun 可是如果进入上面的if 了,它就已经 continue 了,就不会执行下面的 st.push(s[i] - '0'); 加不加 else 应该没什么区别


by changjiahao @ 2022-08-28 21:22:41

菜鸟路过,看见错误了,每个参与运算的数并不只是一位数。

这是我在你的基础上改过之后,能AC的代码。

#include <iostream>
#include <stack>
#include <string>
using namespace std;
stack<long long> st;
string s;
int main()
{
    long long sum = 0,num = 0;
    cin >> s;
    for (int i = 0; i < s.size(); i++)
    {
        long long a, b;
        if (s[i] == '.')
        {
            st.push(num);
            num = 0;
            continue;
        }
        if (s[i] == '@')
        {
            cout << st.top();
            return 0;
        }
        if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/')
        {
            a = st.top();
            st.pop();
            b = st.top();
            st.pop();
            if (s[i] == '+') st.push(a + b);
            if (s[i] == '-') st.push(b - a);
            if (s[i] == '*') st.push(a * b);
            if (s[i] == '/') st.push(b / a);
            continue;
        }
        num = num * 10 + signed(s[i] - '0');
    }
}

by 伏地魔老杨 @ 2022-08-30 11:31:22

@changjiahao 多谢大佬,已关


|