返回

简洁解析 LeetCode 227:JavaScript 版基本计算器 II

前端

如何使用 JavaScript 构建自己的基本计算器

想要自己动手构建一个可以处理各种数学表达式的计算器吗?那就让 JavaScript 来帮你实现吧!

简介

JavaScript 拥有强大的数学运算能力,非常适合用于构建基本计算器。本文将深入探讨如何使用 JavaScript 编写一个能够处理加法、减法、乘法和除法的计算器。

栈数据结构

为了管理操作数和运算符,我们将使用栈数据结构。栈遵循后进先出的(LIFO)原则,非常适合处理嵌套表达式。

运算符优先级

不同的运算符具有不同的优先级。为了确保正确的运算顺序,我们需要使用对象或哈希表来跟踪运算符的优先级。

代码实现

现在,让我们逐步分解代码实现:

// 操作符栈
const operatorStack = [];

// 操作数栈
const operandStack = [];

// 操作符优先级
const precedence = { '+': 1, '-': 1, '*': 2, '/': 2 };

// 处理输入字符串
const input = "(1 + 2) * 3 - 4 / 2";

// 遍历输入字符串
for (let i = 0; i < input.length; i++) {
  // 跳过空格
  if (input[i] === ' ') continue;

  // 如果是数字,则压入操作数栈
  if (!isNaN(parseInt(input[i]))) {
    let number = '';
    while (i < input.length && !isNaN(parseInt(input[i]))) {
      number += input[i];
      i++;
    }
    i--;
    operandStack.push(parseInt(number));
  }

  // 如果是运算符
  else {
    // 比较优先级并弹出相应元素进行计算
    while (operatorStack.length > 0 && precedence[operatorStack[operatorStack.length - 1]] >= precedence[input[i]]) {
      const operator = operatorStack.pop();
      const operand2 = operandStack.pop();
      const operand1 = operandStack.pop();
      const result = calculate(operand1, operand2, operator);
      operandStack.push(result);
    }

    // 压入当前运算符
    operatorStack.push(input[i]);
  }
}

// 计算剩余运算符
while (operatorStack.length > 0) {
  const operator = operatorStack.pop();
  const operand2 = operandStack.pop();
  const operand1 = operandStack.pop();
  const result = calculate(operand1, operand2, operator);
  operandStack.push(result);
}

// 输出结果
console.log(operandStack[0]); // 输出:4

calculate 函数

calculate 函数根据运算符执行实际计算:

function calculate(operand1, operand2, operator) {
  switch (operator) {
    case '+':
      return operand1 + operand2;
    case '-':
      return operand1 - operand2;
    case '*':
      return operand1 * operand2;
    case '/':
      return Math.floor(operand1 / operand2);
  }
}

常见问题解答

  1. 如何处理括号?

本实现中未处理括号。要支持括号,需要使用递归或其他技术来识别括号内的子表达式。

  1. 如何处理浮点数?

默认情况下,calculate 函数仅支持整数。要支持浮点数,需要修改函数以处理小数点和浮点数运算。

  1. 如何处理负数?

输入字符串中的负数应带符号。在实现中,负数应按原样压入操作数栈,并在计算时正确处理符号。

  1. 如何扩展以支持更多运算符?

要扩展计算器以支持更多运算符,只需将新运算符及其优先级添加到 precedence 对象中,并在 calculate 函数中实现相应的运算。

  1. 如何优化代码?

该实现可以通过使用更有效的栈实现或优化计算逻辑来进一步优化。

结论

使用 JavaScript 构建基本计算器是一种有趣且富有教育意义的练习。通过理解栈数据结构和运算符优先级的概念,我们能够编写简洁高效的代码来处理各种数学表达式。希望本文为您的 JavaScript 计算器开发之旅提供了一个坚实的基础。