WA HELP

P1449 后缀表达式

HUTEHE @ 2024-04-08 16:56:37

#include<bits/stdc++.h>
#define int long long
#define ist istringstream
using namespace std;
string ex;
stack<int>st;
int l; 
char zf;
int solve() 
{
    cin>>ex;
    l=ex.size();
    int ll=l-1;
    ist iss(ex);
    while(ll--)
    {
        iss>>zf;
        if(zf=='.')
        {
            continue;
        }
        else if(isdigit(zf)!=0)
        {
            st.push(zf-'0');
        }
        else
        {
            int n2=st.top();
            st.pop();
            int n1=st.top();
            st.pop();
            switch(zf)
            {
                case '+':
                    st.push(n1+n2);
                    break;
                case '-':
                    st.push(n1-n2);
                    break;
                case '*':
                    st.push(n1*n2);
                    break;
                case '/':
                    st.push(n1/n2);
                    break;

            }
        }
    }
    return st.top();
}
signed main()
{
    cout<<solve();
    return 0;
}

why? 测试信息


by liuli688 @ 2024-04-08 17:38:22

@HUTEHE 如果输入数字是多位数,你的程序处理不了。

改进:

#include<bits/stdc++.h>
#define int long long
#define ist istringstream
using namespace std;
string ex;
stack<int>st;
int l,sum; 
char zf;
int solve() 
{
    cin>>ex;
    l=ex.size();
    int ll=l-1;
    ist iss(ex);
    while(ll--)
    {
        iss>>zf;
        if(zf=='.')
        {
            st.push(sum);//压入数字
            sum = 0;//重置
            continue;
        }
        else if(isdigit(zf)!=0)
        {
            sum = sum * 10 + zf - '0';//累加数字
            //st.push(zf-'0');
        }
        else
        {
            int n2=st.top();
            st.pop();
            int n1=st.top();
            st.pop();
            switch(zf)
            {
                case '+':
                    st.push(n1+n2);
                    break;
                case '-':
                    st.push(n1-n2);
                    break;
                case '*':
                    st.push(n1*n2);
                    break;
                case '/':
                    st.push(n1/n2);
                    break;

            }
        }
    }
    return st.top();
}
signed main()
{
    cout<<solve();
    return 0;
}

by HUTEHE @ 2024-04-10 16:33:11

@liuli688 谢谢(这几天没上线,回复有点晚,抱歉)


|