文章

19

粉丝

0

获赞

166

访问

4.2k

头像
计算表达式 题解:

#include <iostream>
#include <stack>
#include <string>
#include <cctype>
#include <map>
using namespace std;

int main()
{
	string s;
	map<char,int> rk;
	rk['+']=1;rk['-']=1;rk['*']=2;rk['/']=2;
	while(cin>>s)
	{
		stack<int> num;
		stack<char> temp;
		for(int i=0;i<s.size();i++)
		{
			if(isdigit(s[i]))
			{
				   // 处理多位数
               int x = 0;
               while (i < s.size() && isdigit(s[i]))
               {
                    x = x * 10 + (s[i] - '0'); // 字符转数字
                    i++;
               }
               num.push(x);
               i--; // 回退一位,因为for循环会自动i++
			   }
			   else
			   {
				   while(!temp.empty()&&rk[s[i]]<=rk[temp.top()])
				   {
					   char c=temp.top();
					   temp.pop();
					   int b=num.top();
					   num.pop();
					   int a=num.top();
					   num.pop();
					   if(c=='+') num.push(a+b);
					   else if(c=='-') n...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发