资源限制
内存限制:256.0MB C/C++时间限制:1.0s Java时间限制:3.0s Python时间限制:5.0s
  编写一个字符串表达式求解函数int expression(char* s); 输入一个字符串表达式,返回它的结果。表达式长度不会超过100。表达式最少有一项,且以等号=结束。表达式中只包含加法和减法,且运算均在整数范围之内。
   编写main函数测试该函数的正确性。
输入:
   2+2345+913-3=
输出:
   3257
#include<iostream>
#include<string>
#include<stack> 
using namespace std;
stack<int> num;//操作数栈
stack<char> op;//运算符栈
void operate(){
	int b=num.top();//右操作数
	num.pop();
	int a=num.top();//左操作数
	num.pop();
	if(op.top()=='+') num.push(a+b);
	if(op.top()=='-') num.push(a-b);
	op.pop();
}
int main(){
	string s;
	cin>>s;
	for(int i=0;i<s.length()-1;i++){//最后一个是“=” 
		if(s[i]>='0'&&s[i]<='9'){//操作数(可能不是个位数,比如12) 
			int j=i;
			int x=0;//操作数
			while(j<s.length()-1&&s[j]>='0'&&s[j]<='9'){
				x=x*10+s[j++]-'0';
			} 
			num.push(x);
			i=j-1;//i指向整个操作数的个位数 
		}else{//运算符 
			if(op.empty()) op.push(s[i]);
			else{
				operate();
				op.push(s[i]);
			} 
		} 
	}
	//剩余
	while(op.size()) operate();
	cout<<num.top()<<endl;
	return 0;
}
思路:中缀表达式的计算。 比中缀表达式求值简单。



















