Created
January 24, 2018 14:17
-
-
Save s4553711/baba2fa044233413271693da77bde833 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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