-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluate_reverse_polish_notation.cpp
72 lines (62 loc) · 1.59 KB
/
evaluate_reverse_polish_notation.cpp
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
// https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/
// Date: Nov 25, 2014
#include <iostream>
#include <cstdlib>
#include <stack>
#include <vector>
using namespace std;
class Solution {
public:
int evalRPN(vector<string> &tokens)
{
stack<int> stk;
for (int i=0; i != tokens.size(); ++i)
{
string token = tokens[i];
int val;
if ( (token == "+") || (token == "-") || (token == "*") || (token == "/"))
{
int b = stk.top();
stk.pop();
int a = stk.top();
stk.pop();
if (token == "+")
{
val = a + b;
}
else if (token == "-")
{
val = a - b;
}
else if (token == "*")
{
val = a * b;
}
else if (token == "/")
{
val = a / b;
}
}
else
{
// token is int
val = atoi(token.c_str());
}
stk.push(val);
}
int result = stk.top();
stk.pop();
return result;
}
};
int main(int argc, char* argv[])
{
string arr[] = {"4", "13", "5", "/", "+"};
vector<string> vec(arr, arr+sizeof(arr)/sizeof(arr[0]));
Solution sln;
int result = sln.evalRPN(vec);
return 0;
}
/*
http://stackoverflow.com/questions/650162/why-switch-statement-cannot-be-applied-on-strings
*/