-
Notifications
You must be signed in to change notification settings - Fork 0
/
Basic Calculator II.cpp
114 lines (114 loc) · 1.71 KB
/
Basic Calculator II.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
class Solution {
public:
string getPostString(string s)
{
string back="";
stack<char> op;
int len=s.length();
for(int i=0;i<len;i++)
{
switch(s[i])
{
case ' ':
break;
case'(':
op.push(s[i]);
break;
case')':
while(!op.empty()&&op.top()!='(')
{
back+=op.top();
op.pop();
}
if(!op.empty()&&op.top()=='(')
op.pop();
break;
case'*':
case'/':
while(!op.empty()&&op.top()!='('&&op.top()!='+'&&op.top()!='-')
{
back+=op.top();
op.pop();
}
op.push(s[i]);
break;
case'+':
case'-':
while(!op.empty()&&op.top()!='(')
{
back+=op.top();
op.pop();
}
op.push(s[i]);
break;
default:
while(i<len&&s[i]>='0'&&s[i]<='9')
{
back+=s[i];
i++;
}
back+='#';//这是一个数的分隔符
i--;
break;
}
}
while(!op.empty())
{
back+=op.top();
op.pop();
}
return back;
}
int calculate(string s) {
string deal=getPostString(s);
cout<<deal<<endl;
stack<int> sta;
int len=deal.length();
int num1,num2,temp=0;
for(int i=0;i<len;i++)
{
switch(deal[i]){
case'*':
num2=sta.top();
sta.pop();
num1=sta.top();
sta.pop();
sta.push(num1*num2);
break;
case'/':
num2=sta.top();
sta.pop();
num1=sta.top();
sta.pop();
sta.push(num1/num2);
break;
case'+':
num2=sta.top();
sta.pop();
num1=sta.top();
sta.pop();
sta.push(num1+num2);
break;
case'-':
num2=sta.top();
sta.pop();
num1=sta.top();
sta.pop();
sta.push(num1-num2);
break;
case'#':
break;
default:
while(i<len&&deal[i]>='0'&&deal[i]<='9')
{
temp=temp*10+(deal[i]-'0');
i++;
}//最终出来这个i肯定是一个#
sta.push(temp);
temp=0;
break;
}
}
return sta.top();
}
};