题解 | #四则运算#

四则运算

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)));    
}()

全部评论

相关推荐

xwqlikepsl:感觉很厉害啊,慢慢找
点赞 评论 收藏
分享
被加薪的哈里很优秀:应该继续招人,不会给你留岗位的
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务