题解 | #表达式求值#

表达式求值

https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 返回表达式的值
     * @param s string字符串 待计算的表达式
     * @return int整型
     */
    int solve(string s) {
        // write code here
        stack<int> st_num;
        stack<char> st_op;
        st_op.push('#');

        int a=0,b=0,number=0,is_num=0;
        int i = 0,n=s.length();
        s+='#';
        char op='#';
        while(i<n||st_op.top()!='#')
        {
            is_num=0;
            number = 0;
            while(s[i]>='0'&&s[i]<='9'&&i<n)
            {
                is_num = 1;
                number = number*10 + (s[i]-'0');
                i++;
            }
            if(is_num==1)
            {
                st_num.push(number);
            }
            op = st_op.top();
            if(op=='#')
            {
                st_op.push(s[i]);
                i++;
            }
            else if(op=='+')
            {
                if(s[i]=='*'||s[i]=='(')
                {
                    st_op.push(s[i]);
                    i++;
                }
                else
                {
                    b = st_num.top();
                    st_num.pop();
                    a = st_num.top();
                    st_num.pop();
                    st_num.push(a+b);
                    st_op.pop();
                }  
            }
            else if(op=='-')
            {
                if(s[i]=='*'||s[i]=='(')
                {
                    st_op.push(s[i]);
                    i++;
                }
                else
                {
                    b = st_num.top();
                    st_num.pop();
                    a = st_num.top();
                    st_num.pop();
                    st_num.push(a-b);
                    st_op.pop();
                }  
            }
            else if(op=='*')
            {
                if(s[i]=='(')
                {
                    st_op.push(s[i]);
                    i++;
                }
                else
                {
                    b = st_num.top();
                    st_num.pop();
                    a = st_num.top();
                    st_num.pop();
                    st_num.push(a*b);
                    st_op.pop();
                }
            }
            else if(op=='(')
            {
                if(s[i]==')')
                {
                    st_op.pop();
                    i++;
                }
                else
                {
                    st_op.push(s[i]);
                    i++;
                }
            }
        }
    return st_num.top();
    }
};

全部评论

相关推荐

12-19 22:04
武汉大学 Java
点赞 评论 收藏
分享
不知道怎么取名字_:两个方向 1.简历针对性准备下 2.面试前也需要准备的 主要还是要看各个公司需求,看公司行业和岗位描述,那里面已经写了对技术的需求,一份简历,不可能和所有嵌入式岗位都匹配的
投递北京经纬恒润科技股份有限公司等公司9个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务