Sample input: tokens = ["2","1","+","3","*"]
Sample output: 9
Here is the code:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> s1;
for(size_t i = 0; i < size(tokens); i++){
if(tokens[i]!= "+"||tokens[i]!= "-"||tokens[i]!= "*"||tokens[i]!= "/") {
cout << tokens[i]; //prints '21+'???
s1.push(stoi(tokens[i]));
}
if(tokens[i]== "+"){
int tmp1 = s1.top();
s1.pop();
int tmp2 = s1.top();
s1.pop();
int res = tmp1 + tmp2;
s1.push(res);
}
if(tokens[i]== "-"){
int tmp1 = s1.top();
s1.pop();
int tmp2 = s1.top();
s1.pop();
int res = tmp1 - tmp2;
s1.push(res);
}
if(tokens[i]== "*"){
int tmp1 = s1.top();
s1.pop();
int tmp2 = s1.top();
s1.pop();
int res = tmp1 * tmp2;
s1.push(res);
}
if(tokens[i]== "/"){
int tmp1 = s1.top();
s1.pop();
int tmp2 = s1.top();
s1.pop();
int res = tmp1 / tmp2;
s1.push(res);
}
}
int tmp = s1.top();
return tmp;
}
};
As you can see in the first iteration of for loop(i=0) for some reason when I try to get the first element of vector ("2") and perform operations with it it does not work because the program thinks that "21+" is the first element of vector.