-
Notifications
You must be signed in to change notification settings - Fork 0
/
227 Basic Calculator II.cpp
48 lines (48 loc) · 1.45 KB
/
227 Basic 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
static int fastio=[](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution {
public:
int calculate(string s) {
int len = s.length();
if (len == 0) return 0;
stack<int> stack;
int currentNumber = 0;
char operation = '+';
for (int i = 0; i < len; i++) {
char currentChar = s[i];
if (isdigit(currentChar)) {
currentNumber = (currentNumber * 10) + (currentChar - '0'); // for continuous number string
}
if (!isdigit(currentChar) && currentChar!=' ' || i == len - 1) {
if (operation == '-') {
stack.push(-currentNumber);
}
else if (operation == '+') {
stack.push(currentNumber);
}
else if (operation == '*') {
int x=stack.top() * currentNumber;
stack.pop();
stack.push(x);
}
else if (operation == '/') {
int x=stack.top() / currentNumber;
stack.pop();
stack.push(x);
}
operation = currentChar;
currentNumber = 0;
}
}
int result = 0;
while (!stack.empty()) {
result += stack.top();
stack.pop();
}
return result;
}
};