题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
//方法一:eval
void async function () {
const str = await readline();
console.log(eval(str.replaceAll("{","(").replaceAll("}",")").replaceAll("[","(").replaceAll("]",")")));
}()
// 方法二:
void async function () {
const str = await readline();
const operatorMap = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 2, "%": 2};//操作符优先级
const isOperand = (c) => /[0-9]/.test(c);//操作数
const isOperator = (c) => /[\+\-\*\/]/.test(c);//操作符
const isLeft = (c) => /[\[\(\{]/.test(c);//左括号
const isRight = (c) => /[\]\)\}]/.test(c);//右括号
// 中缀表达式转逆波兰表达式(后缀表达式)
const infixToPostfix = (str) =>{
let res = [],stack = [];
for(let i = 0; i < str.length; i++){
const c = str.charAt(i);
if(isOperand(c)){
res.push(c);//操作数直接输出
while(i+1<str.length && isOperand(str.charAt(i+1))) res[res.length-1] += str.charAt(++i);//拼接n位数
}else if(isLeft(c)){
stack.push(c);//左括号直接进栈
if(i+1<str.length && str.charAt(i+1) == "-") res.push("0");//3+2*{1+2*[-4/(8-6)+7]}中的-4改为0-4
}else if(isRight(c)){//遇到右括号把栈中不断出栈,直到弹出左括号才停止
while(stack.length>0 && !isLeft(stack[stack.length-1])) res.push(stack.pop());
stack.pop();//左括号弹出并丢弃
}else{
while(stack.length>0 && stack[stack.length-1]!="(" && operatorMap[c] <= operatorMap[stack[stack.length-1]]) res.push(stack.pop());
stack.push(c);
}
}
while(stack.length > 0) res.push(stack.pop());
return res;
}
//根据逆波兰表达式求值
const calculatePostfix = (list) =>{
const stack = [];
for(const item of list){
if(!isOperator(item)){
stack.push(Number(item));
}else{
const second = stack.pop();
const first = stack.pop();
switch (item) {
case "+":
stack.push(first + second);
break;
case "-":
stack.push(first - second);
break;
case "*":
stack.push(first * second);
break;
case "/":
stack.push(first / second);
break;
}
}
}
return stack.pop();
}
console.log(calculatePostfix(infixToPostfix(str)));
}()
查看26道真题和解析
