-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasic_Calculator.cpp
More file actions
38 lines (38 loc) · 1 KB
/
Basic_Calculator.cpp
File metadata and controls
38 lines (38 loc) · 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
class Solution {
public:
int calculate(string s) {
stack<int> stck;
int operand = 0, res = 0, sign = 1, n= s.size();
for(int i=0; i<n; i++){
auto ch = s[i];
if(isdigit(ch)){
operand = 10*operand + (int)(ch-'0');
}
else if(ch == '+'){
res += sign*operand;
sign = 1;
operand = 0;
}
else if(ch=='-'){
res += sign*operand;
sign = -1;
operand = 0;
}
else if(ch == '('){
stck.push(res);
stck.push(sign);
sign = 1;
res = 0;
}
else if(ch == ')'){
res += sign*operand;
res *= stck.top();
stck.pop();
res += stck.top();
stck.pop();
operand = 0;
}
}
return res+(sign*operand);
}
};