题解 | #表达式求值#
表达式求值
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 () { // Write your code here while ((line = await readline())) { let str = line.replaceAll(" ", ""); console.log(eval(str)); // console.log(Function(`return ${str}`)()); return; let strA, strB, strC; let indexLeft, indexRight; let match1; // 1、括号内的优先级最高,先计算括号里的内容 while (str.match(/\(/)) { match1 = str.match(/(\([\+\-\*\/0-9]+\))/); indexLeft = match1["index"]; indexRight = indexLeft + match1[1].length - 1; strA = str.substring(0, indexLeft); strB = str.substring(indexLeft + 1, indexRight); strC = str.substring(indexRight + 1); // 2、括号里的内容在这里运算 strB = String(execVal(strB)); //判断strB是否为负,如果是,则需要把负数提前 if (strB.indexOf("-") >= 0) { strB = strB.substring(1); let isDone = false; let arrA = strA.split(""); for (let i = arrA.length; i >= 0; i--) { if (/[\+|\-]/.test(arrA[i])) { arrA[i] = arrA[i] == "+" ? "-" : "+"; isDone = true; break; } } strA = arrA.join(""); if (!isDone) { strA = "-" + strA; } } str = `${strA}${strB}${strC}`; } // 3、最后不包含括号的内容在这里运算 console.log(Number(execVal(str))); } })(); // 计算不包含括号的内容 var execVal = function (str) { // let matchArr = str.match(/(\w+)([\*\/\+\-])(\w+)/); let a, b, val, sign, strNew; let left, right; let matchArr = str.match(/([\-]?\w+)([\*\/])([\-]?\w+)/); if (!matchArr) { matchArr = str.match(/([\-]?\w+)([\+\-])([\-]?\w+)/); } if (matchArr) { //a,b...,strNew... a = Number(matchArr[1]); b = Number(matchArr[3]); sign = matchArr[2]; switch (sign) { case "*": val = a * b; break; case "/": val = a / b; break; case "+": val = a + b; break; case "-": val = a - b; break; } left = str.substring(0, matchArr["index"]); if (left && !/[\+\-\*\/]/.test(left[left.length - 1])) { //left 如果是个减号,可能会在匹配 matchArr 被 a 拿走 if (val >= 0) { //此时需要根据 val 正负判断需要补充什么,如果为负数自身转换成 String 以后不需要补充符号 // "15+8" + "+" + "0" + right // "15+8" + "-2" + right left += "+"; } } right = str.substring(matchArr["index"] + matchArr[0].length); strNew = `${left}${String(val)}${right}`; // strNew = `${str.substring(0, matchArr['index'])}${String(val)}${str.substring(matchArr['index']+ matchArr['input'])}`; return execVal(strNew); } else { //此时为不带运算符的数字 return str; } };