-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvaluate-Reverse-Polish-Notation.js
61 lines (46 loc) · 1.58 KB
/
Evaluate-Reverse-Polish-Notation.js
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
// Evaluate Reverse Polish Notation
// Solved
// You are given an array of strings tokens that represents a valid arithmetic expression in Reverse Polish Notation.
// Return the integer that represents the evaluation of the expression.
// The operands may be integers or the results of other operations.
// The operators include '+', '-', '*', and '/'.
// Assume that division between integers always truncates toward zero.
// Example 1:
// Input: tokens = ["1","2","+","3","*","4","-"]
// Output: 5
// Explanation: ((1 + 2) * 3) - 4 = 5
class Solution {
/**
* @param {string[]} tokens
* @return {number}
*/
evalRPN(tokens) {
let stack=[]
let operator = ["+","-","*","/"]
for(let i=0; i<tokens.length; i++) {
if(operator.indexOf(tokens[i])>-1) {
let
b = stack.pop(),
a = stack.pop(),
result
if(tokens[i] == "+") {
result = parseInt(a) + parseInt(b)
}
if(tokens[i] == "-") {
result = parseInt(a) - parseInt(b)
}
if(tokens[i] == "*") {
result = parseInt(a) * parseInt(b)
}
if(tokens[i] == "/") {
result = parseInt(a) / parseInt(b)
}
stack.push(result)
}
else stack.push(tokens[i])
}
return Math.floor(stack.pop())
}
}
let inst = new Solution();
console.log(inst.evalRPN(["1","2","+","3","*","4","-"]))