【leetcode】Evaluate Reverse Polish Notation
来源:互联网 发布:linux命令vi怎么退出 编辑:程序博客网 时间:2024/06/06 00:41
链接:https://oj.leetcode.com/problems/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 stringToNumber(string & str){int len = str.length();int result = 0; int i = 0;int factor = 1;if( str[0] == '-'){factor = -1;i = 1;}else if( str[0] == '+'){i = 1;}for(; i < len; ++i){result *= 10;result += str[i] - '0';}return factor*result;}int evalRPN(vector<string> & tokens){int size = tokens.size();if(size <= 0) return 0;vector<int> numStack;int a, b;for(int i = 0; i < size; ++i){string tempstr = tokens.at(i);int operatorType = -1;if( tempstr.compare("+") == 0){operatorType = 0;}else if( tempstr.compare("-") == 0){operatorType = 1;}else if( tempstr.compare("*") == 0){operatorType = 2;}else if( tempstr.compare("/") == 0){operatorType = 3;}else{operatorType = -1;numStack.push_back( stringToNumber(tempstr) );}if( operatorType != -1){b = numStack.back();numStack.pop_back();a = numStack.back();numStack.pop_back();switch(operatorType){case 0:a = a + b;break;case 1:a = a - b;break;case 2:a = a * b;break;case 3:a = a / b;break;}numStack.push_back(a);}}return numStack.back();}
。
0 0
- 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
- LeetCode:Evaluate Reverse Polish Notation
- LeetCode Evaluate Reverse Polish Notation
- Leetcode:Evaluate Reverse Polish Notation
- LeetCode :: Sum Root to Leaf Numbers [tree、dfs]
- 使用对象数组和指针
- 项目开发中是突出的重点重要呢,还是细节重点重要.
- XML详解---1
- 生成验证码时出现Fatal error: Call to undefined function imagettftext()
- 【leetcode】Evaluate Reverse Polish Notation
- 设置Activity进入退出动画
- MySQL基本命令
- VC++ 鼠标事件、键盘事件模拟
- xml 解析
- 利用JavaScript通过单选框radio控制div的显示和隐藏
- 做这个花了两个晚上,感觉不太熟悉,也不太懂 = =
- 使用pthread模拟一个简单线程池
- CMA连续物理内存用户空间映射---(一)