Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
一道混合的题,难度不高,是几个部分组成。
需要注意:
1.转换数字,负数的存在。
2.出栈时数字的顺序。
3.好像没什么了……
class Solution { public: int evalRPN(vector<string> &tokens) { stack<int> sk; int result; for(int i = 0 ; i < tokens.size(); i++) { if(isop(tokens[i])) { int second = sk.top(); sk.pop(); int first = sk.top(); sk.pop(); int midresult; if(tokens[i] == "+") midresult = first + second; else if(tokens[i] == "-")midresult = first - second; else if(tokens[i] == "*")midresult = first * second; else if(tokens[i] == "/")midresult = first / second; sk.push(midresult); } else { int tp = string2num(tokens[i]); sk.push(tp); } } return sk.top(); } bool isop(string s) { if(s== "+" ||s== "-" ||s== "*" ||s== "/" )return 1; else return 0; } int string2num(string s) { int re =0 ; int flag = 0; int i = 0; if(s[0] == '-') { flag =1; i++; } for( ; i < s.size();i++) { re = re*10; re = re + s[i]-'0'; } if(flag ==1) re = 0 -re; return re; } };