后缀表达式的计算

牛牛与后缀表达式

https://ac.nowcoder.com/acm/problem/212914

class Solution {
public:
	/**
	 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
	 *
	 * 给定一个后缀表达式,返回它的结果
	 * @param str string字符串
	 * @return long长整型
	 */
	stack<long long>das;
	char s[1000005];
	string stand = "+-*";

	long long sum = 0;
	long long legalExp(string str) {
		// write code here
		int i;
		for (i = 0; i < str.size(); ++i)
		{
			sum = 0;
            bool flag=false;
			while(isdigit(str[i]))
			{
                flag=1;
				sum = sum * 10 + str[i++] - '0';
			}
            //储存数字
			if(flag){das.push(sum);
            //cout<<das.top()<<" ";
            //如果是读取到数字,才放入栈之中
                    }
			if (stand.find(str[i]) != string::npos)
			{
               //遇到操作符就进行运算,操作符运算对象:离操作符最近的两个栈中的数字
				long long q = das.top();
				das.pop();
				long long h = das.top();
				das.pop();
                //cout<<q<<" "<<h<<" ";
				long long ans{};
				switch (str[i])
				{
					case '+':
						ans += h + q;
                        break;
					case '-':
						ans += h - q;
                        break;
					case '*':
						ans += h * q;
                        break;
				}
				das.push(ans);
               // cout<<das.top()<<endl;
			}
            
		}
		return das.top();
	}
};
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-11 15:08
点赞 评论 收藏
分享
不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 11:31
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

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