Skip to content

Commit 14a4685

Browse files
committedFeb 5, 2025
Add solution #150
1 parent edbe624 commit 14a4685

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@
154154
147|[Insertion Sort List](./0147-insertion-sort-list.js)|Medium|
155155
148|[Sort List](./0148-sort-list.js)|Medium|
156156
149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard|
157+
150|[Evaluate Reverse Polish Notation](./0150-evaluate-reverse-polish-notation.js)|Medium|
157158
151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium|
158159
152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium|
159160
153|[Find Minimum in Rotated Sorted Array](./0153-find-minimum-in-rotated-sorted-array.js)|Medium|
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 150. Evaluate Reverse Polish Notation
3+
* https://leetcode.com/problems/evaluate-reverse-polish-notation/
4+
* Difficulty: Medium
5+
*
6+
* You are given an array of strings tokens that represents an arithmetic expression in a
7+
* Reverse Polish Notation.
8+
*
9+
* Evaluate the expression. Return an integer that represents the value of the expression.
10+
*
11+
* Note that:
12+
* - The valid operators are '+', '-', '*', and '/'.
13+
* - Each operand may be an integer or another expression.
14+
* - The division between two integers always truncates toward zero.
15+
* - There will not be any division by zero.
16+
* - The input represents a valid arithmetic expression in a reverse polish notation.
17+
* - The answer and all the intermediate calculations can be represented in a 32-bit integer.
18+
*/
19+
20+
/**
21+
* @param {string[]} tokens
22+
* @return {number}
23+
*/
24+
var evalRPN = function(tokens) {
25+
const stack = [];
26+
const operators = {
27+
'+': (a, b) => a + b,
28+
'-': (a, b) => a - b,
29+
'*': (a, b) => a * b,
30+
'/': (a, b) => a / b >= 0 ? Math.floor(a / b) : Math.ceil(a / b),
31+
};
32+
33+
tokens.forEach(token => {
34+
if (operators[token]) {
35+
const item = stack.pop();
36+
stack.push(operators[token](stack.pop(), item));
37+
} else {
38+
stack.push(Number(token));
39+
}
40+
});
41+
42+
return stack.pop();
43+
};

0 commit comments

Comments
 (0)
Please sign in to comment.