-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathBasic Calculator II
More file actions
46 lines (41 loc) · 1.18 KB
/
Basic Calculator II
File metadata and controls
46 lines (41 loc) · 1.18 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
/*
Company Tags : Airbnb
Leetcode Link : https://leetcode.com/problems/basic-calculator-ii/
*/
class Solution {
public:
int calculate(string s) {
int n = s.length();
int currNum = 0;
char prevOp = '+';
stack<int> st;
for(int i = 0; i<n; i++) {
if(isdigit(s[i])) {
currNum = currNum*10 + (s[i]-'0');
}
if(s[i] != ' ' && !isdigit(s[i]) || i == n-1) {
if(prevOp == '+') {
st.push(currNum);
} else if(prevOp == '-') {
st.push(-currNum);
} else if(prevOp == '/') {
int x = st.top();
st.pop();
st.push(x/currNum);
} else if(prevOp == '*') {
int x = st.top();
st.pop();
st.push(currNum*x);
}
currNum = 0;
prevOp = s[i];
}
}
int result = 0;
while(!st.empty()) {
result += st.top();
st.pop();
}
return result;
}
};