forked from tangweikun/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
33 lines (29 loc) · 684 Bytes
/
index.ts
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
// HELP:
export const calculate = (s: string) => {
let ans = 0
let num = 0 // single number
let sign = 1
const numStack: any = []
const symStack: any = []
for (let i = 0; i < s.length; i++) {
const item = s[i]
if ('0123456789'.indexOf(item) !== -1) {
num = num * 10 + +item
} else {
ans += sign * num
num = 0
if (item === '+') sign = 1
else if (item === '-') sign = -1
else if (item === '(') {
numStack.push(ans)
symStack.push(sign)
ans = 0
sign = 1
} else if (item === ')') {
ans = symStack.pop() * ans + numStack.pop()
}
}
}
ans += sign * num
return ans
}