-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0150_evalRPN.cc
73 lines (67 loc) · 1.35 KB
/
Problem_0150_evalRPN.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <functional>
#include <iostream>
#include <string>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
int evalRPN(vector<string> &tokens)
{
vector<int> st;
std::function<int(int, int, const string &)> compute = [](int a, int b, const string &cur) -> int
{
if (cur == "+")
{
return a + b;
}
else if (cur == "-")
{
return a - b;
}
else if (cur == "*")
{
return a * b;
}
else
{
return a / b;
}
};
int n = tokens.size();
for (int i = 0; i < n; i++)
{
string cur = tokens[i];
if (cur == "+" || cur == "-" || cur == "*" || cur == "/")
{
int b = st.back();
st.pop_back();
int a = st.back();
st.pop_back();
st.push_back(compute(a, b, cur));
}
else
{
st.push_back(std::stoi(cur));
}
}
return st[0];
}
};
void testEvalRPN()
{
Solution s;
vector<string> t1 = {"2", "1", "+", "3", "*"};
vector<string> t2 = {"4", "13", "5", "/", "+"};
vector<string> t3 = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
EXPECT_EQ_INT(9, s.evalRPN(t1));
EXPECT_EQ_INT(6, s.evalRPN(t2));
EXPECT_EQ_INT(22, s.evalRPN(t3));
EXPECT_SUMMARY;
}
int main()
{
testEvalRPN();
return 0;
}