-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathexpression.cpp
82 lines (82 loc) · 1.2 KB
/
expression.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
struct Exp
{
bool error;
int tot,top;
int num[N];
char op[N];
void ini()
{
error=false;
tot=0;
top=1;
op[1]='(';
}
bool prior(char a,char b)
{
if(b=='+'||b=='-')
return a!='(';
return a=='*'||a=='/';
}
int cal(char c,int a,int b)
{
if(c=='+') return a+b;
if(c=='-') return a-b;
if(c=='*') return a*b;
if(b!=0) return a/b;
error=true;
return 0;
}
bool digit(char ch)
{
return ch>='0'&&ch<='9';
}
int solve(char *s,int len)
{
s[len++]=')';
for(int i=0;i<len;i++)
{
if(s[i]=='(') op[++top]=s[i];
else if(s[i]==')')
{
while(top>0&&op[top]!='(')
{
num[tot-1]=cal(op[top],num[tot-1],num[tot]);
tot--;
top--;
}
top--;
}
else if(s[i]=='-'&&(i==0||s[i-1]=='('))
{
num[++tot]=0;
op[++top]='-';
}
else if(digit(s[i]))
{
int t=s[i]-'0';
for(i++;digit(s[i]);i++)
{
t=t*10+s[i]-'0';
}
num[++tot]=t;
i--;
}
else
{
while(top>0&&prior(op[top],s[i]))
{
num[tot-1]=cal(op[top],num[tot-1],num[tot]);
tot--;
top--;
}
op[++top]=s[i];
}
}
return num[1];
}
}E;
{
E.ini();
int res=E.solve(s,len);//s为表达式
return (res==tmp && !E.error);
}