文章标题
2016-09-12 14:38
218 查看
[leetcode]evaluate-reverse-polish-notation
题目内容
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
分析
题目为分析逆波兰表达式,然后得出结果。即算术表达式的求值过程。题目要求为int类型运算和简单的+-*/四则运算。在除法时需要考虑被除数为0的情况。int evalRPN(vector<string> &tokens) { std::stack<int> stackNum; if(tokens.size() == 0) { return 0; } int a,b; while( !tokens.empty() ) { string str = tokens.front(); tokens.erase(tokens.begin()); if(str == "+") { a = stackNum.top(); stackNum.pop(); b = stackNum.top(); stackNum.pop(); stackNum.push(a+b); } else if(str == "-") { a = stackNum.top(); stackNum.pop(); b = stackNum.top(); stackNum.pop(); stackNum.push(b-a); } else if(str == "*") { a = stackNum.top(); stackNum.pop(); b = stackNum.top(); stackNum.pop(); stackNum.push(a*b); } else if(str == "/") { a = stackNum.top(); stackNum.pop(); b = stackNum.top(); stackNum.pop(); if(a != 0) stackNum.push(b/a); } else { int num = atoi(str.c_str()); stackNum.push(num); } } return stackNum.top(); }