Evaluate Reverse Polish Notation--LeetCode
来源:互联网 发布:spss软件怎么下载 编辑:程序博客网 时间:2024/05/16 11:24
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思路:使用栈这个数据结构,只不过需要字符串和整数整数和字符串之间的转换
#include <iostream>#include <vector>#include <string>#include <stack>using namespace std;int strtoi(string& s){ if(s.length() == 0) return 0; int i=0,flag=1,result=0; if(s[0]=='-') { flag =-1; i++; } if(s[0]=='+') { i++; } for(;i<s.length();i++) { result *= 10; result += (s[i]-'0'); } return result*flag;}string itostr(int num){ int flag =1,count = num; if(num <0) { flag = 0; count = -count; } string result; while(count) { result += (count%10 +'0'); count = count/10; } if(flag == 0) result += '-'; reverse(result.begin(),result.end()); return result; }int evalRPN(vector<string> &tokens) { stack<string> sk; int result =0,i,temp; string first,second; for(i=0;i<tokens.size();i++) { if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/") { first = sk.top(); sk.pop(); second =sk.top(); sk.pop(); if(tokens[i] == "+") temp = strtoi(first)+strtoi(second); else if(tokens[i]=="-") temp = strtoi(first)-strtoi(second); else if(tokens[i]=="*") temp = strtoi(first)*strtoi(second); else temp = strtoi(second)/strtoi(first); first = itostr(temp); sk.push(first); } else sk.push(tokens[i]); } first = sk.top(); result = strtoi(first); return result; }int main(){ string array[]={"4", "13", "5", "/", "+"}; vector<string> tokens(array,array+sizeof(array)/sizeof(array[0])); cout<<evalRPN(tokens)<<endl; system("pause"); return 0; }
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
- 第六周 阅读程序
- java.lang.ref 包分析 引用 弱引用 强引用 虚引用
- eclipse,选中同一个变量
- 黑马程序员--IOS入学学习--4-数组、字符串及指针
- HBase 系统架构
- Evaluate Reverse Polish Notation--LeetCode
- 什么是过度设计?
- opencv视频流的读取和处理
- mac修改环境变量
- 后端JSP文件里Java语言如何操作Oracle Spatial提供的JGeometry对象2
- 第六周 项目六(1):复数模板类
- 关于手写验证码
- VS使用技巧
- 机器学习 Support Vector Machines 1