-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patht227. Basic Calculator II.cpp
More file actions
63 lines (58 loc) · 1.51 KB
/
Copy patht227. Basic Calculator II.cpp
File metadata and controls
63 lines (58 loc) · 1.51 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
#include <bits/stdc++.h>
using namespace std;
int calculate(string s) {
vector<char> op;
vector<int> num;
for(int i=0;i<s.size();i++){
if(s[i]==' ')
continue;
if(s[i]>='0'&&s[i]<='9'){
int temp = 0;
while(i<s.size()&&s[i]>='0'&&s[i]<='9'){
int a = s[i]-'0';
temp = temp*10+a;
i++;
}
int res;
if(!op.empty()){
if(op.back()=='*'){
res = num.back()*temp;
num.pop_back();
num.push_back(res);
op.pop_back();
}else if(op.back()=='/'){
res = num.back()/temp;
num.pop_back();
num.push_back(res);
op.pop_back();
}else{
num.push_back(temp);
}
}else{
num.push_back(temp);
}
i--;
}else{
op.push_back(s[i]);
}
}
int ans = num[0];
if(!op.empty()){
int index = 1;
for(int i=0;i<op.size();i++){
char oper = op[i];
if(oper=='+'){
ans = ans+num[index++];
}else{
ans = ans-num[index++];
}
}
}
return ans;
}
int main(){
//vector<int> v{3,5,9};
int res = calculate("3/2 ");
cout<<res<<endl;
system("pause");
}