-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCPPrefreence.cpp
68 lines (67 loc) · 1.8 KB
/
CPPrefreence.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<iostream>
#include<stack>
using namespace std;
int priv[300];
int value[300];
int calc(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;
if(op=='%')return a%b;
}
int calculate(string str,int val[]=value){
stack <int> num;
stack <char> oper;
priv['+'] = priv['-'] = 3;
priv['*'] = priv['/'] = 2;
priv['%'] = 1,priv['('] = 10;
int x,y,t=0;
int i;char last =0;
for(i=0;i<str.length();i++){
if(isalpha(str[i])){
num.push(val[str[i]]);
}else if(isdigit(str[i])){
num.push(atof(str.c_str()+i));
for(;i+1<str.length()&&isdigit(str[i+1]);i++);
}else if(str[i]=='('){
oper.push(str[i]);
}else if(str[i]==')'){
while(oper.top()!='('){
y=num.top();num.pop();
x=num.top();num.pop();
char op = oper.top();
num.push(calc(x,y,op));
}
oper.pop();
}else if(str[i]=='-'&&(last==0||last=='(')){
num.push(0);
oper.push('-');
}else if(priv[str[i]]>0){
while(oper.size()>0&&priv[str[i]]>=priv[oper.top()]){
y = num.top();num.pop();
x = num.top();num.pop();
char op = oper.top();
oper.pop();
num.push(calc(x,y,op));
}
oper.push(str[i]);
}else continue;
last = str[i];
}
while(oper.size()>0){
y=num.top();num.pop();
x=num.top();num.pop();
char op = oper.top();
oper.pop();
num.push(calc(x,y,op));
}
return num.top();
}
int main(){
string str;
while(cin >> str){
cout << calculate(str);
}
return 0;
}