-
Notifications
You must be signed in to change notification settings - Fork 0
/
227.基本计算器-ii.js
45 lines (43 loc) · 1.11 KB
/
227.基本计算器-ii.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
/*
* @lc app=leetcode.cn id=227 lang=javascript
*
* [227] 基本计算器 II
*/
// @lc code=start
/**
* @param {string} s
* @return {number}
*/
var calculate = function (s) {
let str = s.replace(/\s*/g, "");
const stack = [];
let newNum = 0;
let preSign = "+";
const len = str.length;
for (let i = 0; i < len; i++) {
if (!isNaN(Number(str[i]))) {
newNum = newNum * 10 + Number(str[i]);
}
if (isNaN(Number(str[i])) || i === len - 1) {
switch (preSign) {
case "+":
stack.push(newNum);
break;
case "-":
stack.push(-newNum);
break;
case "*":
stack.push(stack.pop() * newNum);
break;
default:
stack.push(parseInt(stack.pop() / newNum, 10));
break;
}
preSign = str[i];
newNum = 0;
}
}
const result = stack.reduce((prev, next) => prev * 1 + next * 1);
return result;
};
// @lc code=end