Skip to content

计算逆波兰表达式

人们常用中序表达式来进行计算,如 1 + 2,而计算机更擅长使用后续表达式(逆波兰表达式),如 1 2 +

请编写一个函数计算后续表达式。

Code

javascript
/**
 * 计算逆波兰表达式
 * @param {string[]} tokens
 * @returns {number} 计算结果
 */
function evalRPN(tokens) {
  const stack = [];
  for (const token of tokens) {
    if (/\d/.test(token)) {
      // 如果是数字,则转换为 number 类型压入栈中
      stack.push(Number(token));
    } else {
      // 弹出两个操作数
      const a = stack.pop();
      const b = stack.pop();
      // 对两个操作数进行计算,并将计算结果放入栈中
      if (a !== undefined && b !== undefined) {
        switch (token) {
          case '*': {
            stack.push(b * a);
            break;
          }
          case '/': {
            // 仅保留整数部分
            stack.push(Math.trunc(b / a));
            break;
          }
          case '+': {
            stack.push(b + a);
            break;
          }
          case '-': {
            stack.push(b - a);
            break;
          }
        }
      }
    }
  }
  // 弹出最终的计算结果
  return stack.pop();
}

Test Cases

javascript
const { evalRPN } = require('./evalRPN');

describe('evalRPN', () => {
  it('should be 6', () => {
    const tokens = ['4', '13', '5', '/', '+'];
    expect(evalRPN(tokens)).toBe(6);
  });
  it('should be 9', () => {
    const tokens = ['2', '1', '+', '3', '*'];
    expect(evalRPN(tokens)).toBe(9);
  });
  it('should be 22', () => {
    const tokens = ['10', '6', '9', '3', '+', '-11', '*', '/', '*', '17', '+', '5', '+'];
    expect(evalRPN(tokens)).toBe(22);
  });