forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluateReversePolishNotation.cpp
123 lines (103 loc) · 3.06 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// Source : https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/
// Author : Hao Chen
// Date : 2014-06-16
/**********************************************************************************
*
* 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
*
*
**********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class Solution {
#define ERROR err=false;continue
public:
int evalRPN(vector<string> &tokens) {
int i =0;
bool err = false;
vector<int> exp;
for (int i=0; i<tokens.size() && !err; i++ ){
if( isOp(tokens[i])==true ) {
if (exp.size() >= 2) {
int lhs, rhs;
rhs = exp.back();
exp.pop_back();
lhs = exp.back();
exp.pop_back();
int evlValue;
if (tokens[i]=="+"){
evlValue = lhs + rhs;
}else if (tokens[i]=="-"){
evlValue = lhs - rhs;
}else if (tokens[i]=="*"){
evlValue = lhs * rhs;
}else if (tokens[i]=="/"){
evlValue = lhs / rhs;
}
exp.push_back(evlValue);
}else{
ERROR;
}
}else if (isNum(tokens[i])) {
exp.push_back(value);
}else {
ERROR;
}
}
if (err==true){
return 0;
}
if (exp.size()==1){
return exp.back();
}
return 0;
}
private:
long value;
bool isOp(string &op) {
return (op=="+" || op=="-" || op=="*" || op=="/");
}
bool isNum(string &num) {
char *end;
value = strtol(num.c_str(), &end, 10);
if (end == num.c_str() || *end != '\0' || errno == ERANGE){
return false;
}
return true;
}
};
int main()
{
Solution s;
char exps[5][3] = {"42", "9", "6", "-", "+"};
vector<string> expression;
cout << "Expression: \n ";
for (int i=0; i<5; i++){
expression.push_back(exps[i]);
cout << exps[i] << " ";
}
cout << endl;
cout << s.evalRPN(expression)<<endl;;
char exps2[5][3] = {"2", "1", "+", "3", "*"};
expression.clear();
cout << "Expression: \n ";
for (int i=0; i<5; i++){
expression.push_back(exps2[i]);
cout << exps2[i] << " ";
}
cout << endl;
cout << s.evalRPN(expression)<<endl;
return 0;
}