题解 | #表达式求值#

表达式求值

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

全部评论

相关推荐

06-17 21:57
门头沟学院 Java
白友:噗嗤,我发现有些人事就爱发这些,明明已读不回就行了,就是要恶心人
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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