File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ int evalRPN (vector<string> &tokens) {
4+ stack<int > st;
5+ int x, y;
6+ for (int i = 0 ; i < tokens.size (); i++) {
7+ if ((tokens[i][0 ] >= ' 0' && tokens[i][0 ] <= ' 9' ) || (tokens[i].length () > 1 )) {
8+ x = 0 ;
9+ int j = 0 ;
10+ if (tokens[i][0 ] == ' -' ) j++;
11+ for (; j < tokens[i].length (); j++)
12+ x = x * 10 + (tokens[i][j] - ' 0' );
13+ if (tokens[i][0 ] == ' -' ) x = -x;
14+ st.push (x);
15+ } else {
16+ if (st.size () < 2 ) return ERROR_CODE;
17+ x = st.top (), st.pop ();
18+ y = st.top (), st.pop ();
19+ if (tokens[i][0 ] == ' +' ) st.push (x + y);
20+ else if (tokens[i][0 ] == ' -' ) st.push (y - x);
21+ else if (tokens[i][0 ] == ' *' ) st.push (y * x);
22+ else if (tokens[i][0 ] == ' /' && x != 0 ) st.push (y / x);
23+ else return ERROR_CODE;
24+ }
25+ }
26+ return st.empty () ? 0 : st.top ();
27+ }
28+ private:
29+ int ERROR_CODE = -1 ;
30+ };
You can’t perform that action at this time.
0 commit comments