Pagini recente » Cod sursa (job #2345676) | Cod sursa (job #2475177) | Cod sursa (job #630027) | Cod sursa (job #1589523) | Cod sursa (job #2239562)
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<vector>
#include<map>
#include<stack>
#include<queue>
#define MAX_LEN 100005
int doArithmetic(int left,int right,char operation) {
switch(operation) {
case '+':
return left+right;
case '-':
return left-right;
case '*':
return left*right;
case '/':
return left/right;
default:
return 0;
}
}
void applyOperation(std::stack<int>& numbers,std::stack<char>& operators) {
int right=numbers.top();
numbers.pop();
int left=numbers.top();
numbers.pop();
char operation=operators.top();
int tmp=doArithmetic(left,right,operation);
operators.pop();
numbers.push(tmp);
}
int getPrecedence(char operation) {
if(operation=='+' || operation=='-')
return 1;
if(operation=='*' || operation=='/')
return 2;
else
return 0;
}
bool hasPrecedence(char a,char b) {
return getPrecedence(a)>=getPrecedence(b);
}
int evalExpr(char *str) {
std::stack<int> numbers;
std::stack<char> operators;
if(!str)
return -1;
int len=strlen(str);
for(int i=0;i<len;i++) {
char ch=str[i];
if(ch=='(')
operators.push(ch);
else if(ch>='0' && ch<='9') {
int value=0;
for(int j=i;str[j]>='0' && str[j]<='9';j++) {
value=value*10+(str[j]-'0');
i=j;
}
numbers.push(value);
}
else if(ch==')') {
while(!operators.empty() && operators.top()!='(') {
applyOperation(numbers,operators);
}
operators.pop();
}
else {
while(!operators.empty() && hasPrecedence(operators.top(),ch)) {
applyOperation(numbers,operators);
}
operators.push(ch);
}
}
while(!operators.empty()) {
applyOperation(numbers,operators);
}
return numbers.top();
}
int main()
{
FILE *fin,*fout;
fin=fopen("evaluare.in","r");
fout=fopen("evaluare.out","w");
char str[MAX_LEN];
fscanf(fin,"%s",str);
int result=evalExpr(str);
fprintf(fout,"%d\n",result);
fclose(fin);
fclose(fout);
return 0;
}