Evaluate Reverse Polish Notation [leetcode]

 
 
    一个很简单的题目,但是浪费了我半天时间,原因是字符串与数字之间的转化不熟练,c++常用函数不熟悉。刚开始自己编写函数转换,后来使用istringstream和ostringstream输入输出流转换,再后来用c++库函数转换(使用起来很简单)。废话不说,上题目。

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 strToint(string s)
{
    int sum=0;
    int j=0;
    for(int i=s.size()-1;i>=0;i--)
    {
        if(s[i]!='-')
        {
            sum+=(s[i]-'0')*pow(10.0,j);
            j++;
        }else{
            sum=-sum;
        }

    }
    return sum;
}
string intToStr(int aa)
{
    int a=abs(aa);
    string res="";
    int digital[10];
    int n=0;
    int b=a%10;
    digital[n]=b;
    n++;
    while(a/10)
    {
        a=a/10;
        b=a%10;
        digital[n]=b;
        n++;
    }
    if(aa<0)
        res.push_back('-');
    for(int i=n-1;i>=0;i--)
    {
        res.push_back('0'+digital[i]);
    }
    return res;
}
方法二、使用stringstream流

	template<class T>
	string tostr(const int &t)  // to_stirng()
	{
		ostringstream os;
		os << t;
		return os.str();
	}

	template<class T>
	int tonum(const string s)  // stoi()
	{
		istringstream is(s);
		int x;
		is >> x;
		return x;
	}
方法三、使用c++标准库函数

to_string(typename t)  //数字转字符串
atoi(string s)  //字符串转数字



下面是完整程序,visual studio 2013 通过,leetcode accept

#include <iostream>
#include <vector>
#include <string>
#include <stack>
using namespace std;

class Solution {
public:
	int evalRPN(vector<string> &tokens) {
		std::stack<string> sk;
		for (vector<string>::iterator it = tokens.begin(); it<tokens.end(); it++)
		{
			if (*it != "+" && *it != "-" && *it != "*" && *it != "/")
			{
				sk.push(*it);
			}
			else
			{
				if (*it == "+")
				{
					int a = stoi(sk.top());
					sk.pop();
					int b = stoi(sk.top());
					sk.pop();
					sk.push(to_string(a + b));
				}
				if (*it == "-")
				{
					int a = stoi(sk.top());
					sk.pop();
					int b = stoi(sk.top());
					sk.pop();
					sk.push(to_string(b - a));
				}
				if (*it == "*")
				{
					int a = stoi(sk.top());
					sk.pop();
					int b = stoi(sk.top());
					sk.pop();
					sk.push(to_string(a*b));
				}
				if (*it == "/")
				{
					int a = stoi(sk.top());
					sk.pop();
					int b = stoi(sk.top());
					sk.pop();
					sk.push(to_string(b / a));
				}
			}
		}

		return stoi(sk.top());

	}
};

int main()
{
	Solution s;
	vector<string> v{ "2", "1", "+", "3", "*" };
	cout<<s.evalRPN(v);
	return 0;
}


你可能感兴趣的:(Evaluate Reverse Polish Notation [leetcode])