关闭

Leetcode: Evaluate Reverse Polish Notation

标签: LeetcodeReverse Polish Notat
2576人阅读 评论(0) 收藏 举报
分类:

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




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1073674次
    • 积分:12632
    • 等级:
    • 排名:第1137名
    • 原创:268篇
    • 转载:59篇
    • 译文:4篇
    • 评论:326条
    我是博主
    最新评论