Skip to content

Instantly share code, notes, and snippets.

@s4553711
Created January 24, 2018 14:17
Show Gist options
  • Save s4553711/baba2fa044233413271693da77bde833 to your computer and use it in GitHub Desktop.
Save s4553711/baba2fa044233413271693da77bde833 to your computer and use it in GitHub Desktop.
class Solution {
public:
int calculate(string s) {
s += "+";
stack<int> st;
char old = '+';
for(int i = 0, left = 0; i < s.size(); i++) {
if (isdigit(s[i]) || isspace(s[i])) continue;
int val = stoi(s.substr(left, i-left));
if (old == '+' || old == '-') st.push(old == '+' ? val : -val);
else st.top() = (old == '*' ? st.top()*val : st.top()/val);
old = s[i];
left = i+1;
}
int ans = 0;
while(!st.empty()) {
ans += st.top();
st.pop();
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment