day 28: 155-min-stack, 150-evaluate-reverse-polish-notation

This commit is contained in:
2023-10-29 19:14:36 -07:00
parent ec5227eae8
commit 392b6c97e9
6 changed files with 121 additions and 0 deletions

View File

@@ -0,0 +1,10 @@
#include "soln.hpp"
int main()
{
vector<string> tokens{"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
int answer = 22;
Solution soln;
cout << "Evaluated postfix expression correctly? " << soln.test(tokens, answer) << endl;
return 0;
}

View File

@@ -0,0 +1,42 @@
#include "soln.hpp"
int Solution::evalRPN(vector<string> &tokens)
{
vector<int> operands;
int a, b;
for (int i = 0; i < tokens.size(); i++)
{
if (tokens[i].length() > 1 || isdigit(tokens[i][0]))
{
operands.push_back(stoi(tokens[i]));
}
else
{
b = operands.back();
operands.pop_back();
a = operands.back();
operands.pop_back();
switch (tokens[i][0])
{
case '+':
operands.push_back(a + b);
break;
case '-':
operands.push_back(a - b);
break;
case '*':
operands.push_back(a * b);
break;
case '/':
operands.push_back(a / b);
break;
}
}
}
return operands[0];
}
bool Solution::test(vector<string> &tokens, int answer)
{
return evalRPN(tokens) == answer;
}

View File

@@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int evalRPN(vector<string> &tokens);
bool test(vector<string> &tokens, int answer);
};