Skip to content

Commit 0678797

Browse files
authored
Update 224-basic-calculator.js
1 parent 53a7f4b commit 0678797

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

224-basic-calculator.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,49 @@ const calculate = function(s) {
7777

7878
return res + op * num
7979
};
80+
81+
// another
82+
/**
83+
* @param {string} s
84+
* @return {number}
85+
*/
86+
const calculate = function(s) {
87+
s = s.trim()
88+
89+
let res = 0, num = 0, op = 1
90+
const isDigit = ch => ch >= '0' && ch <= '9'
91+
const stk = []
92+
for(let i = 0, n = s.length; i < n; i++) {
93+
94+
const e = s[i]
95+
if(e === ' ') continue
96+
if(isDigit(e)) num = num * 10 + (+e)
97+
else {
98+
99+
if(e === '(') {
100+
stk.push(res)
101+
stk.push(op)
102+
103+
res = 0
104+
num = 0
105+
op = 1
106+
} else if(e === ')') {
107+
res += num * op
108+
res *= stk.pop()
109+
res += stk.pop()
110+
op = 1
111+
num = 0
112+
} else if(e === '-') {
113+
res += num * op
114+
op = -1
115+
num = 0
116+
} else if(e === '+') {
117+
res += num * op
118+
op = 1
119+
num = 0
120+
}
121+
}
122+
}
123+
124+
return res + num * op
125+
};

0 commit comments

Comments
 (0)