-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathevaluate-reverse-polish-notation.js
96 lines (88 loc) · 2.37 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
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
/**
* Source: https://leetcode.com/problems/evaluate-reverse-polish-notation/
* Tags: [Stack]
* Level: Medium
* Title: Evaluate Reverse Polish Notation
* Auther: @imcoddy
* Content: 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
*/
/**
* @param {string[]} tokens
* @return {number}
*/
/**
* Memo: Use stack and pop operands
* Complex: O(n)
* Runtime: 164ms
* Tests: 20 test cases passed
* Rank: B
* Updated: 2015-06-11
*/
var evalRPN = function(tokens) {
var stack = [];
for (var i = 0; i < tokens.length; i++) {
if (!isNaN(tokens[i])) {
stack.push(tokens[i]);
} else {
var b = stack.pop();
var a = stack.pop();
token = tokens[i];
var result;
if (token === '+') {
result = parseInt(a, 10) + parseInt(b, 10);
} else if (token === '-') {
result = parseInt(a, 10) - parseInt(b, 10);
} else if (token === '*') {
result = parseInt(a, 10) * parseInt(b, 10);
} else if (token === '/') {
result = ~~(parseInt(a, 10) / parseInt(b, 10));
}
stack.push(result);
}
}
return parseInt(stack.pop(), 10);
};
/**
* Memo: Use javascript feature to pass arguments
* Complex: O(n)
* Runtime: 132ms
* Tests: 20 test cases passed
* Rank: S
* Updated: 2015-06-11
*/
var evalRPN = function(tokens) {
var stack = [];
var map = Object.create(null);
map['+'] = function(b, a) {
return a + b;
};
map['-'] = function(b, a) {
return a - b;
};
map['*'] = function(b, a) {
return a * b;
};
map['/'] = function(b, a) {
return ~~(a / b);
};
for (var i = 0; i < tokens.length; i++) {
stack.push(isNaN(tokens[i]) ? map[tokens[i]](parseInt(stack.pop(), 10), parseInt(stack.pop(), 10)) : tokens[i]);
}
return parseInt(stack.pop(), 10);
};
var should = require('should');
console.time('Runtime');
evalRPN(["2", "1", "+", "3", "*"]).should.equal(9);
evalRPN(["4", "13", "5", "/", "+"]).should.equal(6);
console.timeEnd('Runtime');