Basic Calculator II LeetCode solution in C++

1
class Solution {
2
public:
3
int calculate(string s) {
4
stack<int> nums;
5
stack<char> ops;
6
int n = 0;
7
for (int i = 0; i < s.size(); ++i) {
8
if (s[i] >= '0' && s[i] <= '9') {
9
string t(1, s[i]);
10
n = n * 10 + stoi(t);
11
} else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {
12
nums.push(n);
13
n = 0;
14
if (!ops.empty() && (ops.top() == '*' || ops.top() == '/')) {
15
int n2 = nums.top();
16
nums.pop();
17
int n1 = nums.top();
18
nums.pop();
19
if (ops.top() == '*')
20
nums.push(n1 * n2);
21
else
22
nums.push(n1 / n2);
23
ops.pop();
24
}
25
ops.push(s[i]);
26
}
27
}
28
nums.push(n);
29
if (!ops.empty() && (ops.top() == '*' || ops.top() == '/')) {
30
int n2 = nums.top();
31
nums.pop();
32
int n1 = nums.top();
33
nums.pop();
34
if (ops.top() == '*')
35
nums.push(n1 * n2);
36
else
37
nums.push(n1 / n2);
38
ops.pop();
39
}
40
stack<int> tnums;
41
stack<char> tops;
42
while (!nums.empty()) {
43
tnums.push(nums.top());
44
nums.pop();
45
}
46
while (!ops.empty()) {
47
tops.push(ops.top());
48
ops.pop();
49
}
50

51
while (!tops.empty()) { // cout<<tops.top()<<" " ;
52
int n1 = tnums.top();
53
tnums.pop();
54
int n2 = tnums.top();
55
tnums.pop();
56
if (tops.top() == '+')
57
tnums.push(n1 + n2);
58
else
59
tnums.push(n1 - n2);
60
tops.pop();
61
}
62
return tnums.top();
63
}
64
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0