题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
// 方法一:简单题?简单做
void (async function () {
console.log(eval(await readline()));
})();
// 方法二:栈+递归 400+(100/5)+5
void (async function () {
const str = await readline();
const calculate = (str) => {
const stack = [];
let ops = "+";
for (let i = 0; i < str.length; i++) {
const c = str.charAt(i);
if (/\d/.test(c)) {
let num = c;
while(i+1<str.length && /\d/.test(str.charAt(i+1))) num += str.charAt(++i);
stack.push(Number(num));
} else if (c === "(") {
let sub = "",cnt = 1;
while(i+1<=str.length && cnt > 0) {
sub += str.charAt(++i);
if(str.charAt(i+1) == ")") cnt --;
if(str.charAt(i+1) == "(") cnt ++;
}
stack.push(Number(calculate(sub)));
} else {
ops = c;
continue;
}
switch(ops){
case "+":
break;
case "-":
stack.push(stack.pop()*(-1));
break;
case "*":
{
let second = stack.pop();
stack.push(stack.pop()*second);
break;
}
case "/":
{
let second = stack.pop();
stack.push(stack.pop()/second);
break;
}
}
}
return stack.reduce((pre,cur)=>pre+cur,0);
};
console.log(calculate(str));
})();