题解 | #表达式求值#

表达式求值

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

全部评论

相关推荐

03-01 21:45
中北大学 golang
孤蓝长空:请你说一下为什么你用websocket而不是http,请你说一下什么是rpc,为什么用rpc,你的rpc的传输协议是JSON,xml还是什么 请你描述一下你的鉴权流程(完整的) 我问的是第二个项目,随便问的哈哈哈
开工第一帖
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务