Evaluate Reverse Polish Notation
2014-02-26 09:30
405 查看
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
class Solution { public: int evalRPN(vector<string> &tokens) { stack<int> st; int len = tokens.size(); int i = 0; int tem; while(i<len) { if(!isdigit(tokens[i][0])&&tokens[i].length()==1) { switch(tokens[i][0]) { case '+': tem = st.top(); st.pop(); tem +=st.top(); st.top() = tem; break; case '-': tem = st.top(); st.pop(); tem =st.top() - tem; st.top() = tem; break; case '*': tem = st.top(); st.pop(); tem *=st.top(); st.top() = tem; break; case '/': tem = st.top(); st.pop(); tem =st.top()/tem; st.top() = tem; break; default: break; } } else { tem = atoi(tokens[i].c_str()); st.push(tem); } i++; } return st.top(); } };说明:1. 字符串string str, 转化成c格式的操作:str.c_str();2. 字符串变整数,包括符号了, 负数也可以atoi(str.c_str());3.str可以当作数组操作
相关文章推荐
- Palindrome Number
- Max Points on a Line
- Evaluate Reverse Polish Notation
- Sort List
- Insertion Sort List
- LRU Cache
- Binary Tree Postorder Traversal
- Binary Tree Preorder Traversal
- Reorder List
- Linked List Cycle
- Linked List Cycle II
- Word Break
- Word Break II
- Copy List with Random Pointer
- Single Number
- Single Number II
- Candy
- Gas Station
- Clone Graph
- Palindrome Partitioning