leetcode_Evaluate Reverse Polish Notation
来源:互联网 发布:大数据安全与隐私保护 编辑:程序博客网 时间:2024/06/05 10:23
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
计算逆波兰式的值,计算符号只有加减乘除,一看就是需要用到栈模拟,遇到算术符号,就从顶部取数据进行计算,再压入结果。主要注意输入是字符串,需要变成对应数字,一个技巧就是读入到输入输出流中,如下str2num,num2str,十分方便。
class Solution {public: int evalRPN(vector<string> &tokens) { return (int) solve(tokens); } long str2num(string s) { long num; stringstream ss(s); ss>>num; return num; } string num2str(long i) { stringstream ss; ss<<i; return ss.str(); } long solve(vector<string> & tokens) { stack<string> s; for(vector<string>::iterator it = tokens.begin();it!=tokens.end();it++) { if (*it=="+" || *it=="-" || *it =="*" || *it=="/") { long op1,op2,op3; op2 = str2num(s.top()); s.pop(); op1 = str2num(s.top()); s.pop(); if (*it=="+") op3 = op1 + op2; else if(*it=="-") op3 = op1 - op2; else if(*it=="*") op3 = op1 * op2; else op3 = op1 / op2; string str=num2str(op3); s.push(str); } else{ s.push(*it); } } return str2num(s.top()); }};
0 0
- 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
- LeetCode_evaluate-reverse-polish-notation
- Reverse Polish Notation
- calculate 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
- easymock单元测试实例二
- c# 读xml文件
- WinCE驱动编写小结
- wxListCtrl的基本用法
- C与C++的兼容问题——extern "C"的用法解析
- leetcode_Evaluate Reverse Polish Notation
- Platform Builder实践之两个要点(by fllsoft)
- 如何修改tomcat7的端口和用户名密码?
- Platform Builder实践之文件系统(by fllsoft)
- Platform Builder实践之文件系统(by fllsoft)
- 33 Android 获取版本等信息
- vs2013下配置jrtplib
- HDU 1061(快速幂取模)
- jquery: Uncaught TypeError: Object [object Object] has no method 'live'