Pagini recente » Cod sursa (job #2781125) | Cod sursa (job #2598121) | Cod sursa (job #521080) | Cod sursa (job #3187308) | Cod sursa (job #2774901)
#include <bits/stdc++.h>
#define ll long long
#define lsb(x) x & -x
using namespace std;
int getPriority(char c) {
if(c == '+' || c == '-')
return 1;
if(c == '*' || c == '/')
return 2;
return 0;
}
int getResult(int a, int b, char op) {
if(op == '+')
return a + b;
if(op == '-')
return a - b;
if(op == '/')
return a / b;
if(op == '*')
return a * b;
}
void compute(stack<int> &values, stack<char> &operators) {
int a = values.top();
values.pop();
int b = values.top();
values.pop();
int result = getResult(b, a, operators.top());
operators.pop();
values.push(result);
}
int getNumber(int &index, const string &s) {
int number = 0;
while(index < s.size() && '0' <= s[index] && s[index] <= '9') {
number *= 10;
number += (s[index] - '0');
index ++;
}
return number;
}
int main() {
ifstream cin("evaluare.in");
ofstream cout("evaluare.out");
string s;
cin >> s;
stack<char> operators;
stack<int> values;
int index = 0;
while(index < s.size()) {
if('0' <= s[index] && s[index] <= '9')
values.push(getNumber(index, s));
else if(s[index] == '(') {
operators.push(s[index]);
index ++;
} else if(s[index] == ')') {
while(operators.top() != '(')
compute(values, operators);
operators.pop();
index ++;
} else if(getPriority(s[index]) > 0) {
while(operators.size() && getPriority(operators.top()) > 0 && getPriority(s[index]) <= getPriority(operators.top())) {
compute(values, operators);
}
operators.push(s[index]);
index ++;
}
}
while(operators.size())
compute(values, operators);
cout << values.top();
return 0;
}