mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2026-01-25 07:34:05 +00:00
day 28: 155-min-stack, 150-evaluate-reverse-polish-notation
This commit is contained in:
10
150-evaluate-reverse-polish-notation/driver.cpp
Normal file
10
150-evaluate-reverse-polish-notation/driver.cpp
Normal 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;
|
||||
}
|
||||
42
150-evaluate-reverse-polish-notation/soln.cpp
Normal file
42
150-evaluate-reverse-polish-notation/soln.cpp
Normal 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;
|
||||
}
|
||||
8
150-evaluate-reverse-polish-notation/soln.hpp
Normal file
8
150-evaluate-reverse-polish-notation/soln.hpp
Normal 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);
|
||||
};
|
||||
Reference in New Issue
Block a user