Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

基本计算器 II #238

Open
louzhedong opened this issue Apr 16, 2021 · 0 comments
Open

基本计算器 II #238

louzhedong opened this issue Apr 16, 2021 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。

整数除法仅保留整数部分。

示例 1:

输入:s = "3+2*2"
输出:7
示例 2:

输入:s = " 3/2 "
输出:1
示例 3:

输入:s = " 3+5 / 2 "
输出:5

提示:

1 <= s.length <= 3 * 105
s 由整数和算符 ('+', '-', '*', '/') 组成,中间由一些空格隔开
s 表示一个 有效表达式
表达式中的所有整数都是非负整数,且在范围 [0, 231 - 1] 内
题目数据保证答案是一个 32-bit 整数

思路

用栈来保存之前的操作符,先处理乘法和除法,再处理加法和减法

解答

/**
 * @param {string} s
 * @return {number}
 */
var calculate = function (s) {
  s = removeSpace(s);
  var stack = [],
    len = s.length,
    i = 0,
    j = 1;
  for (; i < len; i++) {
    var current = s[i];
    if (current == ' ') {
      continue;
    } else if (current == '/') {
      var divisor = stack.pop();
      stack.push(Math.floor(Number(divisor) / Number(s[i + 1])));
      i++;
    } else if (current == '*') {
      var multiplier = stack.pop();
      stack.push(Number(multiplier) * Number(s[i + 1]));
      i++;
    } else {
      stack.push(current);
    }
  }
  var result = Number(stack[0]);
  for (; j < stack.length; j++) {
    if (stack[j] == '+') {
      result += Number(stack[j + 1]);
      j++;
    } else if (stack[j] == '-') {
      result -= Number(stack[j + 1]);
      j++;
    }
  }
  return result;
};

var removeSpace = function (s) {
  var res = [];
  var currentNumber = '';
  for (var i = 0; i < s.length; i++) {
    var current = s[i];
    if (current != ' ') {
      if (
        current == '+' ||
        current == '-' ||
        current == '*' ||
        current == '/'
      ) {
        res.push(current);
      } else {
        if (currentNumber) {
          current = Number(currentNumber) * 10 + Number(current);
        }
        if ((i + 1) < s.length && !isNaN(s[i + 1]) && s[i + 1] != ' ') {
          currentNumber = current;
        } else if ((i + 1) < s.length && isNaN(s[i + 1]) && s[i + 1] != ' ') {
          res.push(current);
          currentNumber = '';
        } else {
          res.push(current);
        }
      }
    }
  }
  return res;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant