Evaluate Reverse Polish Notation
来源:互联网 发布:《梦里花落知多少》txt 编辑:程序博客网 时间:2024/05/29 07:22
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: /** * @param tokens The Reverse Polish Notation * @return the value */ int evalRPN(vector<string>& tokens) { // Write your code here int n = tokens.size(); if (n < 2) { return stoi(tokens[0]); } stack<int> buf; int first, second; for (int i = 0; i < n; i++) { if (isOperand(tokens[i])) { second = buf.top(); buf.pop(); first = buf.top(); second = cal(first, second, tokens[i]); buf.pop(); buf.push(second); } else { buf.push(stoi(tokens[i])); } } return second; }private: bool isOperand(string a) { if (a == "+" || a == "-" || a == "*" || a == "/") { return true; } return false; } int cal(int a, int b, string c) { if (c == "+") { return a + b; } else if (c == "-") { return a - b; } else if (c == "*") { return a * b; } else { return a / b; } } };
0 0
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- RESTful API 设计最佳实践
- UVA 11916 Emoogle Grid(模指数方程)
- 什麼是REST跟RESTful?
- URAL 1353 Milliard Vasya's Function(数位DP)
- C语言类型强制转换
- Evaluate Reverse Polish Notation
- 文章标题
- 2011 Asia Fuzhou Regional Contest
- [leetCode] Rotate Array
- C/C++ 数字转化为字符串函数
- MySQL优化必须调整的10项配置
- 竖着显示的“UIPageControl”
- Objective_C设计模式
- BroadcastReceiver开机启动