-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy path227-Basic-Calculator-II.js
More file actions
43 lines (37 loc) · 909 Bytes
/
Copy path227-Basic-Calculator-II.js
File metadata and controls
43 lines (37 loc) · 909 Bytes
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
// 227. Basic Calculator II
// https://leetcode.com/problems/basic-calculator-ii/
/**
* @param {string} s
* @return {number}
*/
const calculate = (s) => {
let string = s.replace(/ /g, '');
let operator = '+';
let i = 0;
let stack = [];
let temp = 0;
let start = 0;
while (i < string.length) {
if (!isNaN(+string[i])) {
start = i;
while (i < string.length && (!isNaN(+string[i]) || string[i] === '.')) {
i++;
}
i--;
temp = parseFloat(string.substring(start, i + 1));
if (operator === '+') {
stack.push(temp);
} else if (operator === '-') {
stack.push(-temp);
} else if (operator === '*') {
stack.push(stack.pop() * temp);
} else {
stack.push(Math.trunc(stack.pop() / temp));
}
} else {
operator = string[i];
}
i++;
}
return stack.reduce((p, c) => p + c, 0);
};