forked from tangweikun/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
36 lines (30 loc) · 705 Bytes
/
index.ts
File metadata and controls
36 lines (30 loc) · 705 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
// HELP:
export const calculate2 = (s: string) => {
s = s.replace(/\s/g, '')
const stack = []
let sign = '+'
let res = 0
let num = 0
for (let i = 0; i < s.length; i++) {
if (s[i] >= '0' && s[i] <= '9') {
num = num * 10 + +s[i]
}
if (i == s.length - 1 || !(s[i] >= '0' && s[i] <= '9')) {
if (sign == '+') {
stack.push(num)
} else if (sign == '-') {
stack.push(-num)
} else if (sign == '*') {
stack.push(stack.pop() * num)
} else if (sign == '/') {
stack.push(~~(stack.pop() / num))
}
num = 0
sign = s[i]
}
}
for (var i = 0; i < stack.length; i++) {
res += stack[i]
}
return res
}