LeetCode::Evaluate Reverse Polish Notation

3 篇文章 0 订阅
3 篇文章 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
#include<iostream>
#include<vector>
#include<string>
#include<iterator>
#include<stack>
#include<stdlib.h>
#include <sstream>
using namespace std;
class Solution {
	public:
	int evalRPN(vector<string> &tokens) {
	stack<string> s;
	string token;
	for(vector<string>::iterator it = tokens.begin(); it != tokens.end(); it++)
	{
		token = *it;
		if (!is_operator(*it)) 
		{
			s.push(*it);
		} 
		else 
		{
			if (s.empty())
				return 0;//验证表达式是否正确
			int y = string_to_number(s.top());
			s.pop();
			if (s.empty())
				return 0;
			int x = string_to_number(s.top());
			s.pop();
			if (token[0] == '+') x += y;
			else if (token[0] == '-') x -= y;
			else if (token[0] == '*') x *= y;
			else 
			{
				if(y == 0)
					return 0;//除数不能为零
				x /= y;
			}
			s.push(n_to_string(x));
		}
	}
	return string_to_number(s.top());
	}
	private:
	bool is_operator(const string &op) {
		return op.size() == 1 && string("+-*/").find(op) != string::npos;
	}
	int string_to_number(string &s)
	{
		int Result;
		istringstream convert(s); // stringstream used for the conversion constructed with the contents of 'Text' 
        // ie: the stream will start containing the characters of 'Text'
		if ( !(convert >> Result) ) //give the value to 'Result' using the characters in the stream
		Result = 0;             //if that fails set 'Result' to 0
		return Result;
	}
	string n_to_string(int num)
	{
		string Result;          // string which will contain the result
		ostringstream convert;   // stream used for the conversion
		convert << num;      // insert the textual representation of 'Number' in the characters in the stream
		Result = convert.str(); // set 'Result' to the contents of the stream
         // 'Result' now is equal to "123" 
		return Result;
	}
};

int main()
{
	Solution evaluate;
	vector<string> rp_Expression;
	int value;
	string expression;
	while(cin >> expression)
	{
		rp_Expression.push_back(expression);
	}
	cout << "rp_Expression.size = " << rp_Expression.size() << endl;
	cout << "rp_Expression.front = " << rp_Expression.front() << endl;
	cout << "rp_Expression.back = " << rp_Expression.back() << endl;
	value = evaluate.evalRPN(rp_Expression);
	cout << value << endl;
	return 0;
}


注意事项:
1、验证表达式的正确性
2、除数不能为零
3、加法与乘法满足交换律,减法与除法不满足交换律,因此将出栈的两个操作数调换进行加减乘除运算位置即可。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值