1. 程式人生 > >leed-code2 反向爛lamda表示式四則運算

leed-code2 反向爛lamda表示式四則運算

在反向波蘭表示法中計算算術表示式的值。
有效的運算子是+, - ,*,/。 每個運算元可以是整數或另一個表示式。

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

思路:數字入棧,遇到符號,彈棧兩個數,進行運算,運算完的數在入棧。c++彈棧返回void 所以要先top在pop

atoi(string.c_str()))可轉換為整形(c)。   stoi(string)  (c++)

#include"iostream"
#include"string"
#include"algorithm"
#include"stack"
#include <sstream> 
#include"vector"

using namespace std;

class Solution {
private:
	bool isNum(string s, int *t)
	{
		int a;
		stringstream sin(s);
		if (!(sin >> a))   //將string s轉換為int到t中,成功非0,失敗為0
			return false;
		else
			*t = a;
		return true;
	}
private:
	int get(int a, int b, string operator_str) {
		if (operator_str == "+")
			return a + b;
		if (operator_str == "-")
			return a - b;
		if (operator_str == "*")
			return a*b;
		if (operator_str == "/")
			if (b == 0)
				throw 1;
			else
				return a / b;
		else
			throw 2;
	}
public:
	int evalRPN(vector<string> &tokens) {
		stack<int>s;
		int temp;
		for (auto i = 0; i < tokens.size(); i++)
		{
			if (isNum(tokens[i], &temp))
				s.push(temp);
			else
			{
				int a = s.top();
				s.pop();
				int b = s.top();
				s.pop();
				try {
					s.push(get(b, a, tokens[i]));
				}
				catch (int e) {
					switch (e)
					{
					case 1:
						cout << "/0" << endl;
						break;
					case 2:
						cout << "+-*/" << endl;
						break;
					}
				}
			}
		

		}
		return s.top();
	}
};

void main_test()
{
	Solution s;
	vector<string>v1 = { "4","13","5","/","+" };
	vector<string>v2 = { "2","1","+","3","*" };
	cout << s.evalRPN(v1);
	cout << s.evalRPN(v2);
	system("pause");
}