View Code of Problem 94

#include<iostream>
#include<stack>
#include<vector>
#include<cmath>
using namespace std;
int main() {
	string str;
	getline(cin,str);
	stack<char> s;
	vector<int> v;
	int result;
	for(int i=0; i<str.length();) {
		if(str[i]=='('||str[i]=='+'||str[i]=='-'
		||str[i]=='*'||str[i]=='/') {
			s.push(str[i]);//进栈 
		}else if(str[i]==')') {//碰到右括号
			while(s.top()!='+'&&s.top()!='-'&&
			s.top()!='*'&&s.top()!='/') {
				v.push_back(s.top());
				s.pop();//出栈 
			}
			char c=s.top();//运算符
			s.pop();//出栈运算符 
			result=v[v.size()-1];
			v.pop_back();
			//计算
			if(c=='+') {
				while(v.size()>0) {
					result+=v[v.size()-1];
					v.pop_back();
				}
			}else if(c=='-') {
				while(v.size()>0) {
					result-=v[v.size()-1];
					v.pop_back();
				}
			}else if(c=='*') {
				while(v.size()>0) {
					result*=v[v.size()-1];
					v.pop_back();
				}
			}else {
				while(v.size()>0) {
					result/=v[v.size()-1];
					v.pop_back();
				}
			}
			s.pop();//出栈右括号 
			s.push(result);//入栈结果 
		}else {//空格或者数字 
			if(str[i]!=' ') {//如果是数字 
				string num="";//用来记录数字 
				num+=str[i];
				while(str[i+1]!=' '&&str[i+1]!=')') {
					i++;
					num+=str[i];
				}
				int n=0,j=num.length()-1,p=0;
				while(j>=0) {
					n+=pow(10,p++)*(num[j]-'0'); 
					j--;
				}
				s.push(n);//将数字放入栈中 
			}
		}
		i++; 
	}
	result=s.top();
	cout<<result<<endl;	
} 

Double click to view unformatted code.


Back to problem 94