-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet227.cpp
More file actions
61 lines (48 loc) · 1.12 KB
/
leet227.cpp
File metadata and controls
61 lines (48 loc) · 1.12 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
#include <iostream>
#include <string>
#include <stack>
using namespace std;
class Solution {
public: int calculate(string s) {
if (s.size() == 0) {
return 0;
}
int num = 0, res = 0, top = 0;
char op = '+';
stack<int> mystk;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (isdigit(c)) {
num = num * 10 + c - '0';
}
if ((i == s.size() - 1) || (!isdigit(c) && c != ' ')) {
if (op == '+') {
mystk.push(num);
} else if (op == '-') {
mystk.push(-num);
} else if (op == '*') {
top = mystk.top() * num;
mystk.pop();
mystk.push(top);
} else if (op == '/') {
top = mystk.top() / num;
mystk.pop();
mystk.push(top);
}
op = c;
num = 0;
}
}
while (!mystk.empty()) {
res += mystk.top();
mystk.pop();
}
return res;
}
};
int main(){
string s = "3+2*2";
Solution sol;
int res = sol.calculate(s);
cout << res << endl;
}