hackersun007的修行之路

多写代码,多看书,多思考,吾将上下而求索之...

Leetcode: 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 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();
    }




阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/doc_sgl/article/details/17101519
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭