-
Notifications
You must be signed in to change notification settings - Fork 0
/
calc.js
50 lines (41 loc) · 1.04 KB
/
calc.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
46
47
48
49
50
function del(s) {
const s2 = s.slice(0, -1);
return s2;
}
function isOP(c) {
return c === '+' || c === '-' || c === '/' || c === '*';
}
function is_digit(c){
return '0' <= c && c <= '9';
}
function evaluate1(s) {
const st = [];
const n = s.length;
let num = 0;
let curOp = '+';
for(let i=0; i<n; ++i) {
const curChar = s[i];
if(is_digit(curChar)) {
num = (num*10) + Number(curChar);
}
if(isOP(curChar) || i === n-1) {
if(curOp === '-') {
st.push(-1*num);
}
else if(curOp === '+') {
st.push(num);
}
else if(curOp === '*') {
let top = st.pop();
st.push(top*num);
}
else if(curOp === '/') {
let top = st.pop();
st.push(Math.trunc(top/num));
}
num = 0;
curOp = curChar;
}
}
return (st.reduce((acc, el)=>acc+el)).toString();
}