-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_calculator.cpp
More file actions
46 lines (42 loc) · 1.1 KB
/
Copy pathbasic_calculator.cpp
File metadata and controls
46 lines (42 loc) · 1.1 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
class Solution {
public:
long calculate(string s) {
stack<long> st;
long result = 0, number = 0, sign = 1;
for(char c : s) {
if(isdigit(c)) {
number = number * 10 + (c - '0');
}
else if(c == '+') {
result += sign * number;
sign = 1;
number = 0;
}
else if(c == '-') {
result += sign * number;
sign = -1;
number = 0;
}
else if(c == '(') {
st.push(result);
st.push(sign);
result = 0;
sign = 1;
}
else if(c == ')') {
result += sign * number;
if(!st.empty()) {
result *= st.top();
st.pop();
}
if(!st.empty()) {
result += st.top();
st.pop();
}
number = 0;
}
}
result += sign * number;
return result;
}
};