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

//经典的数据结构问题,逆波兰表达式的计算,由于没有括号,
//所以,利用stack,每次将遇到的操作数push,当遇到操作符的时候
//pop两次top的元素,然后根本操作符来将这两个元素进行运算。
class Solution {
public:
	int evalRPN(std::vector<std::string> &tokens) {
		std::stack<int> number;
		for(std::vector<std::string>::iterator it = tokens.begin(); it != tokens.end(); it++)
		{
			std::string tmp = *it;
			if((tmp[0] == '-' && tmp.size() > 1) || ('0' <= tmp[0] && tmp[0] <= '9'))
			{
				number.push(atoi(tmp.c_str()));
			}
			else
			{
				int b = number.top();
				number.pop();
				int a = number.top();
				number.pop();
				switch (tmp[0])
				{
				case '+':number.push(a+b);break;
				case '-':number.push(a-b);break;
				case '*':number.push(a*b);break;
				case '/':if(b == 0) return 0;number.push(a/b);break;
				default:
					break;
				}
			}
		}
#if 1
		std::cout << number.top() << std::endl;
#endif // 1

		return number.top();
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值