View Code of Problem 94

#include<iostream>
#include<stack>
#include<string>
#include<cctype>

using namespace std;

int main() {
	stack <int>deep;
	stack <int>num;
	stack <int>num2;
	stack <char>c;

	string s;
	int sum = 0;
	char t;
	getline(cin, s);

	int d = 0;
	int D;
	c.push(s[0]);
	for (int i = 1; i <= s.size(); ++i) {
		if (s[i] == '(') {
			c.push(s[i]);
			deep.push(d);
			d = 0;
		}
		else if (isdigit(s[i])) {
			num.push(s[i]-'0');
			++d;
		}
		else if (s[i] == ' ') {
			continue;
		}
		else if (s[i] == ')') {
			t = c.top();
			c.pop();
			c.pop();
			for (int i = 0; i < d; ++i) {
				num2.push(num.top());
				num.pop();
			}
			int sum = num2.top();
			num2.pop();
			while (--d) {
				if (t == '*') {
					sum *= num2.top();
				}
				else if (t == '/') {
					sum /= num2.top();
				}
				else if (t == '-') {
					sum -= num2.top();
				}
				else if (t == '+') {
					sum += num2.top();
				}
				num2.pop();
			}
			num.push(sum);
			if (!c.empty()) {
				d = deep.top();
				++d;
				deep.pop();
			}
		}
		else {
			c.push(s[i]);
		}
	}
	cout << num.top();
}

Double click to view unformatted code.


Back to problem 94