-
Notifications
You must be signed in to change notification settings - Fork 0
/
Basic Calculator.cpp
45 lines (42 loc) · 1.24 KB
/
Basic Calculator.cpp
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
class Solution {
public:
void cal_num(stack<int>& nums, char op){
int num2 = nums.top();
nums.pop()
int num1 = nums.top();
nums.pop();
switch (op) {
case '+': nums.push(num1 + num2);return;
case '-': nums.push(num1 - num2);return;
case '*': nums.push(num1 * num2);return;
case '/': nums.push(num1 / num2);return;
}
}
int calculate(string s) {
int size = s.size();
stack<int> nums;
stack<char> opers;
int t; //
for(int i = 0; i < size; i++){
if(s[i] == '(') opers.push(s[i]);
if(s[i] == '+' || s[i] == '-' || s[i] == ')' ){
nums.push(t);
t = 0;
if (!opers.empty()){
char op = opers.top();
opers.pop();
else cal_num(nums, opers.top());
}
if(s[i] == ')') opers.pop();
else opers.push(s[i]);
}
t += t*10 + s[i] - '0';
}
if(t != '') nums.push(t);
while(!opers.empty()){
cal_num(nums, opers.top());
opers.pop();
}
return nums.top();
}
};