有大神能帮我看看吗,这道题表达式求值(无括号)最终结果对10000取余,但是代码时间超限并且结果错误。能帮我优化一些吗?

#include <bits/stdc++.h>
using namespace std;
stack <char> st;
stack <int> st1;
string a,b;
int num(char n){
    if(n=='+')return 1;
    if(n=='-')return 1;
    if(n=='*')return 2;
    if(n=='/')return 2;
}
int main(){
    cin>>a;
    int lena,lenb,flag=0,x=0,i=0;
    lena=a.length();
    while(i<lena){
        while(a[i]>='0'&&a[i]<='9'){
            b=b+a[i];
            i++;
        }
        b=b+' ';
        if(a[i]=='+'||a[i]=='-'||a[i]=='*'||a[i]=='/'){
            if(st.empty()){
                st.push(a[i]);
            }
            else if(num(a[i])>num(st.top())){
                st.push(a[i]);
            }
            else{
                while(!st.empty()&&num(a[i])<=num(st.top())){
                    b=b+st.top();
                    b=b+' ';
                    st.pop();
                }
                st.push(a[i]);
            }
        }
        i++;
    }
    while(!st.empty()){
            b=b+st.top();
            b=b+' ';
            st.pop();
    }
    lenb=b.length();
    int s1,s2;
    i=0;
    while(i<lenb){
        while(b[i]>='0'&&b[i]<='9'){
            if(flag==0){
                x=(int)(b[i]-'0');
                flag=1;
            }else{
                x=x*10+(int)(b[i]-'0');
            }
            i++;
        }
        if(b[i]==' '&&flag==1){
            st1.push(x);
            flag=0;
        }
        i++;
        if(b[i]=='+'||b[i]=='-'||b[i]=='*'||b[i]=='/'){
            s2=st1.top();
            st1.pop();
            s1=st1.top();
            st1.pop();
            if(b[i]=='+'){
                st1.push(s1+s2);
            }else if(b[i]=='-'){
                st1.push(s1-s2);
            }else if(b[i]=='*'){
                st1.push(s1*s2);
            }else{
                st1.push(s1/s2);
            }
            i++;         
        }
    }
    cout<<st1.top()%10000;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值