Leetcode: Evaluate Reverse Polish Notation

原创 2013年12月03日 21:07:39

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 evalRPN(vector<string> &tokens) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(tokens.size()==1)return stoi(*tokens.begin());
        stack<int> numbers;
		vector<string>::iterator it = tokens.begin();
		int op1 = 0;
		int op2 = 0;
		while(it != tokens.end())
		{
			if(*it == "+"||*it == "-" || *it == "*" || *it == "/")
			{
				op2 = numbers.top();
				numbers.pop();
				op1 = numbers.top();
				numbers.pop();
				if(*it == "+")
					numbers.push(op1+op2);
				else if(*it == "-")
					numbers.push(op1-op2);
				else if(*it == "*")
					numbers.push(op1*op2);
				else
					numbers.push(op1/op2);
			}
			else
				numbers.push(stoi(*it));
			it++;
		}
		return numbers.top();
    }




版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode–Evaluate Reverse Polish Notation

LeetCode–Evaluate Reverse Polish Notation (LeetCode - 评价逆波兰表示法,即后缀表达式) By X Wang (LeetCode: 一个在线编...

[leetcode]Evaluate Reverse Polish Notation题解

描述 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are ...

[C++]LeetCode: 98 Evaluate Reverse Polish Notation

题目: Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators...

(leetcode)Evaluate Reverse Polish Notation

Evaluate Reverse Polish Notation 题目 Evaluate the value of an arithmetic expression in Reverse Pol...
  • fcunren
  • fcunren
  • 2014年08月18日 15:28
  • 278

leetcode笔记:Evaluate Reverse Polish Notation(逆波兰式的计算)

该题考查逆波兰式,也叫后缀表达式(将运算符写在操作数之后)。假设有一个表达式E,其后缀形式定义如下: 1. 如果E是一个变量或常量,则E的后缀式是E本身; 2. 如果E是E1 operator E...

LeetCode 150. Evaluate Reverse Polish Notation

LeetCode 150. Evaluate Reverse Polish Notation 栈

LeetCode|Evaluate Reverse Polish Notation

题目 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are ...
  • hwb1992
  • hwb1992
  • 2014年04月20日 21:26
  • 603

LeetCode:《Evaluate Reverse Polish Notation》

#include #include #include #include using namespace std; class Solution { public: int evalRP...

leetcode 150. Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -...

[LeetCode]Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +,...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Leetcode: Evaluate Reverse Polish Notation
举报原因:
原因补充:

(最多只允许输入30个字)