-
Notifications
You must be signed in to change notification settings - Fork 1
/
EvaluateReversePolishNotation.cpp
90 lines (82 loc) · 2.42 KB
/
EvaluateReversePolishNotation.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
*/
class Solution {
public:
int str2int(string str)
{
bool negative = false;
int i=0;
while(str[i]==' ')
i++;
if(str[i]=='-')
{
negative = true;
i++;
}
int result = 0;
for(;i<str.length();i++)
result = result*10+(str[i]-'0');
return negative?(-1)*result:result;
}
int evalRPN(vector<string> &tokens) {
int len = tokens.size();
if(len<=0)
return 0;
stack<int> result;
for(int i=0;i<len;i++)
{
string str = tokens[i];
if(str.compare("+")!=0&& str.compare("*")!=0 &&str.compare("/")!=0 &&str.compare("-")!=0)
result.push(str2int(str));
else
{
if(str.compare("+")==0) // pay attention to str.compare()
{
int res = 0;
for(int j=0;j<2;j++)
{
int num = result.top();
result.pop();
res +=num;
}
result.push(res);
}
else if(str.compare("-")==0)
{
int res = 0;
int num1 = result.top();
result.pop();
int num2 = result.top();
result.pop();
result.push(num2-num1);
}
else if(str.compare("*")==0)
{
int res = 1;
for(int j=0;j<2;j++)
{
int num = result.top();
result.pop();
res *=num;
}
result.push(res);
}
else if(str.compare("/")==0)
{
int res = 0;
int num1 = result.top();
result.pop();
int num2 = result.top();
result.pop();
result.push(num2/num1);
}
}
}
return result.top();
}
};