码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--Evaluate Reverse Polish Notation

时间:2015-01-15 13:00:38      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:leetcode   stack   逆波兰数   

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

class Solution 
{
public:
    int evalRPN(vector<string> &tokens) 
    {
        stack<int> data;
        for(int i=0; i<tokens.size(); i++)
        {
            if(tokens[i]=="+" || tokens[i]=="-" || tokens[i]=="*" || tokens[i]=="/")
			{
				int second = data.top();
				data.pop();
				int first = data.top();
				data.pop();
				if(tokens[i]=="+")
					data.push(first+second);
				else if(tokens[i]=="-")
					data.push(first-second);
				else if(tokens[i]=="*")
					data.push(first*second);
				else
					data.push(first/second);
			}
			else
				data.push(string_to_int(tokens[i]));
        }
		return data.top();
    }
	int string_to_int(string s)
	{
		int res=0;
		int i=0;
		if(s[0] == '-')
			i=1;
		for(;i<s.length(); i++)
			res = res*10 + s[i]-48;
		if(s[0] == '-')
			res = -res;
		return res;
	}
};


LeetCode--Evaluate Reverse Polish Notation

标签:leetcode   stack   逆波兰数   

原文地址:http://blog.csdn.net/shaya118/article/details/42738595

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!