LeetCode OJ Evaluate Reverse Polish Notation
来源:互联网 发布:淘宝网店在哪里看 编辑:程序博客网 时间:2024/06/11 01:34
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) { vector<int> stack_int; for (int i = 0; i < tokens.size(); i++) { int x, y; if ('0' <= tokens[i][tokens[i].size() - 1] && tokens[i][tokens[i].size() - 1] <= '9') { stack_int.push_back(string_to_num(tokens[i])); } else { y = stack_int.back(); stack_int.pop_back(); x = stack_int.back(); stack_int.pop_back(); if (tokens[i][0] == '+') { stack_int.push_back(x + y); } else if (tokens[i][0] == '-') { stack_int.push_back(x - y); } else if (tokens[i][0] == '*') { stack_int.push_back(x * y); } else if (tokens[i][0] == '/') { stack_int.push_back(x / y); } } } return stack_int.back(); } int string_to_num(string input) { int sum = 0; int positive = 1; int i = 0; if (input[0] == '-') { positive = -1; i = 1; } for (; i < input.size(); i++) { sum = sum * 10 + input[i] - '0'; } return sum * positive; }};
0 0
- LeetCode OJ:Evaluate Reverse Polish Notation
- Leetcode OJ: Evaluate Reverse Polish Notation
- LeetCode OJ Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation | leetcode
- leetcode-Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- LeetCode - Evaluate Reverse Polish Notation
- LeetCode | Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation (LeetCode)
- leetcode: Evaluate Reverse Polish Notation
- Leetcode Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation -- LeetCode
- 【LeetCode】Evaluate Reverse Polish Notation
- LeetCode-Evaluate Reverse Polish Notation
- hdu 4463 Outlets(最小生成树)
- linux 下实线文件切割--split
- LeetCode OJ Remove Duplicates from Sorted List II
- 如何让基于对话框的MFC程序一运行起来就完全隐藏
- LeetCode OJ 3Sum Closest
- LeetCode OJ Evaluate Reverse Polish Notation
- LeetCode OJ Text Justification
- hdu 1548 A strange lift(bfs)
- (大数据之hadoop)hadoop2.2.0的伪分布式安装说明
- LeetCode OJ Reverse Words in a String
- 机器人技术—基于DELPHI的数据采集与分析类上位机软件的编写
- Xcode下使用SVN教程
- Chat-online
- UVA - 12532 Interval Product