-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLesson20.cpp
More file actions
96 lines (89 loc) · 1.72 KB
/
Lesson20.cpp
File metadata and controls
96 lines (89 loc) · 1.72 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include<bits/stdc++.h>
using namespace std;
bool isop(char c)
{
//cout<<"in isop function"<<endl;
if(c=='+'|| c=='-'|| c=='*' || c=='/')
{
//cout<<"returning true;"<<endl;
return true;
}
//cout<<"returning false;"<<endl;
return false;
}
bool isnum(char v)
{
//cout<<"in isnum function"<<endl;
if(v>='0' && v<='9')
{
//cout<<"returning true;"<<endl;
return true;
}
//cout<<"returning false;"<<endl;
return false;
}
int dooper(char d, int op2, int op1)
{
//cout<<"in dooper function"<<endl;
if(d=='+')
{
return op2+op1;
}
else if(d=='-')
{
return op1-op2 ;
}
else if(d=='*')
{
return op1*op2 ;
}
else if (d=='/')
{
return op1/op2 ;
}
return 0;
}
int evaluation (string d)
{
//cout<<"in evaluation function"<<endl;
stack<int>st;
for(int i=0;i<d.size();i++)
{
if(d[i]==' ')
{
continue;
}
else if(isnum(d[i]))
{
//cout<< "detecting the integer number"<<endl;
int sum=0;
while(isnum(d[i]))
{
sum=sum*10+(d[i]-'0');
i++;
}
//cout<<"pushed"<<sum<<endl;
st.push(sum);
i--;
}
else if(isop(d[i]))
{
int op2=st.top();
st.pop();
int op1=st.top();
st.pop();
int res=dooper(d[i],op2,op1);
//cout<<"pushed"<<res<<endl;
st.push(res);
}
}
return st.top();
}
int main()
{
string s="2 3 * 4 5 * + 9 -";
//cin>>s;
int res=evaluation(s);
cout<<res;
// 2 3 * 4 5 * + 9 -
}