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
下面代码在牛客网没有通过,但是感觉逻辑是对的,在vs里也输入了几个例子进行了测试,不知道没有通过的原因是不是我写的太繁琐了。
思路:定义一个栈存放数字,如果遇到运算符,就取栈最上层的两个数进行运算,然后再将运算结果压入栈。
代码:
class Solution {
public:
int evalRPN(vector<string> &tokens) {
if (tokens.size()<=0)
return 0;
stack<int> st;
int a = 0, b = 0, res = 0;
for (int i = 0; i < tokens.size(); ++i) {
string cur = tokens[i];
if (!isoperator(tokens[i]) && !isnumber(tokens[i]))
return 0;
if (isnumber(cur))
st.push(strtoint(cur));
else if (isoperator(cur)) {
b = st.top();//先取到的是第二个操作数
st.pop();
a = st.top();
st.pop();
res = computab(a, b, cur);
st.push(res);
}
}
return res;
}
//执行运算符的操作
int computab(int a, int b, string operate) {
if (operate[0] == '+')
return a + b;
else if (operate[0] == '-')
return a - b;
else if (operate[0] == '*')
return a * b;
else if (operate[0] == '/')
return a / b;
return 0;
}
//判断是否是运算符
bool isoperator(string x) {
if (x.size() == 1 && (x[0] == '+' || x[0] == '-' || x[0] == '*' || x[0] == '/'))
return true;
else
return false;
}
//判断是否是数字
bool isnumber(string x) {
if (x.size() <= 0)
return false;
for (int i = 0; i < x.size(); ++i) {
if (x[i] >= '0' && x[i] <= '9')
continue;
else
return false;
}
return true;
}
//把字符串里的数字转换成int
int strtoint(string x) {
if (x.size() <= 0)
return 0;
int res = x[0] - '0';
for (int i = 1; i < x.size(); ++i) {
res = res * 10 + (x[i] - '0');
}
return res;
}
};
字符串里的数字转换成int的两种写法
1、一位一位转换
int strtoint(string x) {
if (x.size() <= 0)
return 0;
int res = x[0] - '0';
for (int i = 1; i < x.size(); ++i) {
res = res * 10 + (x[i] - '0');
}
return res;
}
2、用stringstream
stringstream ss;
ss << str;
int temp;
ss >> temp;//注意这里别写成temp>>ss
cout << temp << endl;