题解 | #表达式求值#

表达式求值

http://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d

思路

本题使用第50题的解法处理,统一使用双栈

  • 构建运算符对象,增加优先级
  • 构建取出两个数和一个运算符计算的函数
  • 构建主函数,初始化双栈

代码

const opsMap = {
  "+": 1,
  "-": 1,
  "*": 2,
  "/": 2,
};

const calc = (nums = [], ops = []) => {
//   console.log(nums, ops)
  if (nums.length < 2 || ops.length === 0) return;
  const op = ops.pop();
  const b = ~~nums.pop();
  const a = ~~nums.pop();
//   console.log(op, a, b)

  switch (op) {
    case "+":
      nums.push(a + b);
      break;
    case "-":
      nums.push(a - b);
      break;
    case "*":
      nums.push(a * b);
      break;
    default:
      nums.push(a / b);
  }
};

const calculator = (str = "") => {
  const cs = str.split("");
  const nums = [0];
  const ops = [];

  for (let i = 0; i < cs.length; i++) {
    let c = cs[i];
    if (c === "(") {
      // 入栈
      ops.push("(");
      if (cs[i + 1] === "-" || cs[i + 1] === "+") {
        nums.push(0);
      }
    } else if (c === ")") {
      while (ops.length) {
        if (ops[ops.length - 1] !== "(") {
          calc(nums, ops);
        } else {
          ops.pop();
          break;
        }
      }
    } else {
      if (/\d/.test(c)) {
        while (i + 1 < cs.length && /\d/.test(cs[i + 1])) {
          c += cs[i + 1];
          i++;
        }
        nums.push(c);
      } else {
        // 加减乘除
        while (ops.length && ops[ops.length - 1] !== "(") {
          // 根据优先级进行运算
          const topOp = ops[ops.length - 1];
          if (opsMap[topOp] >= opsMap[c]) {
            calc(nums, ops);
          } else {
            break;
          }
        }
        ops.push(c);
      }
    }
  }
  while (ops.length) calc(nums, ops);
  return nums[nums.length - 1];
};

while(input = readline()) {
  console.log(calculator(input))
}

全部评论

相关推荐

02-17 20:43
西北大学 Java
醉蟀:别浪费时间。老板是一个想入行互联网的新人。去年6 7月boss上面看到的。他把所有人都拉到一个微信群,然后一个一个面,自己也在学技术。公司就是一个小区里面租的两间房。都没有买电脑啥的。
点赞 评论 收藏
分享
2024-12-26 20:46
复旦大学 C++
国棉17厂丶小王:拿了offer的那个周末晚上去网吧通宵,去网吧不知道玩什么刷了lc的每日一题,然后试着第一次打开了三角洲行动,从此少了一个已经刷了700道题的lc用户,但是烽火地带多了一只🐭🐭
点赞 评论 收藏
分享
评论
18
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务