-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator II .cpp
76 lines (69 loc) · 2.07 KB
/
calculator II .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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class Solution {
public:
int calculate(string s) {
stack<int> operands;
stack<char> operators;
for (int i = 0; i < s.size(); i++) {
if (s[i] == ' ') {
continue;
} else if (isdigit(s[i])) {
int count = 0;
while (i < s.size() && isdigit(s[i])) {
count = count * 10 + (s[i] - '0');
i++;
}
i--;
operands.push(count);
} else if (s[i] == '(') {
operators.push('(');
} else if (s[i] == ')') {
while (operators.top() != '(') {
func2(operands, operators);
}
operators.pop();
} else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {
while (!operators.empty() && func1(s[i], operators.top())) {
func2(operands, operators);
}
operators.push(s[i]);
}
}
while (!operators.empty()) {
func2(operands, operators);
}
return operands.top();
}
private:
bool func1(char op1, char op2) {
if (op2 == '(' || op2 == ')') {
return false;
} else if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) {
return false;
}
return true;
}
void func2(std::stack<int>& operands, std::stack<char>& operators) {
int b = operands.top();
operands.pop();
int a = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
int flag;
switch (op) {
case '+':
flag = a + b;
break;
case '-':
flag = a - b;
break;
case '*':
flag = a * b;
break;
case '/':
flag = a / b;
break;
}
operands.push(flag);
}
};