Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 487275f

Browse files
committed
Add solution #227
1 parent 01813e3 commit 487275f

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

0227-basic-calculator-ii.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 227. Basic Calculator II
3+
* https://leetcode.com/problems/basic-calculator-ii/
4+
* Difficulty: Medium
5+
*
6+
* Given a string s which represents an expression, evaluate this expression and return its value.
7+
*
8+
* The integer division should truncate toward zero.
9+
*
10+
* You may assume that the given expression is always valid. All intermediate results will be in
11+
* the range of [-231, 231 - 1].
12+
*
13+
* Note: You are not allowed to use any built-in function which evaluates strings as mathematical
14+
* expressions, such as eval().
15+
*/
16+
17+
/**
18+
* @param {string} s
19+
* @return {number}
20+
*/
21+
var calculate = function(s) {
22+
const stack = [];
23+
24+
for (let i = 0, num = 0, sign = '+'; i < s.length; i++) {
25+
if (s[i] >= '0' && s[i] <= '9') num = num * 10 + (s[i] - '0');
26+
if ((s[i] < '0' && s[i] !== ' ') || i === s.length - 1) {
27+
if (sign === '+') stack.push(num);
28+
else if (sign === '-') stack.push(-num);
29+
else if (sign === '*') stack.push(stack.pop() * num);
30+
else if (sign === '/') stack.push(Math.trunc(stack.pop() / num));
31+
sign = s[i];
32+
num = 0;
33+
}
34+
}
35+
36+
return stack.reduce((a, b) => a + b, 0);
37+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,7 @@
208208
224|[Basic Calculator](./0224-basic-calculator.js)|Hard|
209209
225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy|
210210
226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy|
211+
227|[Basic Calculator II](./0227-basic-calculator-ii.js)|Medium|
211212
228|[Summary Ranges](./0228-summary-ranges.js)|Easy|
212213
229|[Majority Element II](./0229-majority-element-ii.js)|Medium|
213214
230|[Kth Smallest Element in a BST](./0230-kth-smallest-element-in-a-bst.js)|Medium|

0 commit comments

Comments
 (0)