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) //字符串转数字
#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; }