-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path224_basicCalculator.cpp
48 lines (47 loc) · 1.14 KB
/
224_basicCalculator.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
class Solution {
private:
bool isDigit(char ch){
if(ch>='0' && ch<='9') return true;
return false;
}
public:
int calculate(string s) {
int n = s.size();
int sign = 1;
int ans = 0;
stack<int> st;
string cur="";
for(int i=0; i<n; i++){
if(s[i]==' ') continue;
else if(isDigit(s[i])){
while(isDigit(s[i])){
cur += s[i];
i++;
}
ans += stoi(cur)*sign;
--i;
}
else if(s[i]=='+'){
cur = "";
sign = 1;
}
else if(s[i]=='-'){
cur = "";
sign = -1;
}
else{
if(s[i]=='('){
st.push(ans);
st.push(sign);
ans = 0;
sign = 1;
}
else if(s[i]==')'){
ans = ans*st.top(); st.pop();
ans += st.top(); st.pop();
}
}
}
return ans;
}
};