Pagini recente » Cod sursa (job #2615967) | Cod sursa (job #1055289) | Cod sursa (job #3150423) | Cod sursa (job #2588872) | Cod sursa (job #2876072)
#include <iostream>
#include <stack>
#include <fstream>
#include <cstring>
using namespace std;
const int mod = 1e9;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
stack<int> numbers;
stack<char> operators;
int precedence(char o) {
if (o == '*' || o == '/')
return 2;
if (o == '-' || o == '+')
return 1;
return 0;
}
int op(int a, int b, char o) {
switch (o) {
case '+':
return a + b;
case '-':
return a - b;
case '/':
return a / b;
case '*':
return a * b;
}
}
void apply(){
int val1 = numbers.top();
numbers.pop();
int val2=numbers.top();
numbers.pop();
numbers.push(op(val2, val1, operators.top()) % mod);
operators.pop();
}
int evaluate(char s[]) {
int l=strlen(s);
for (int i = 0; i < l; i++) {
if (s[i] >= '0' && s[i] <= '9') {
int n = 0, j;
for (j = i; s[j] <= '9' && s[j] >= '0'; j++)
n = n * 10 + s[j] - '0';
i = j - 1;
numbers.push(n);
}
else if (s[i] == '(')
operators.push('(');
else if (s[i] == ')') {
while (operators.top() != '(') {
apply();
}
operators.pop();
} else {
while (!operators.empty() && precedence(operators.top()) >= precedence(s[i])) {
apply();
}
operators.push(s[i]);
}
}
while (!operators.empty()) {
apply();
}
return numbers.top();
}
int main() {
char expr[100001];
in.getline(expr, 100001);
out<<evaluate(expr);
return 0;
}