“This is the 21st day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

Leetcode 227. Basic Calculator II

The title

Given a string expression s, you implement a basic calculator to evaluate and return its value.

Integer division preserves only integer parts.

Example 1:

Input: s = “3+2*2” Output: 7

Example 2:

Input: s = “3/2” Output: 1

Example 3:

Input: s = “3+ 5/2” Output: 5

 

Tip:

1 <= s.length <= 3 * 105 s consists of integers and operators (‘+’, ‘-‘, ‘*’, ‘/’) separated by Spaces. S indicates a valid expression. All integers in the expression are non-negative integers. And the question data in the range [0, 231-1] guarantees that the answer is a 32-bit integer

Answer key

Ask questions

  • How do I divide a stringsSpace in?
  • How do I read numbers?
  • How to multiply and divide before adding and subtracting?

Analysis of the

  • As you can see from the question, the string S contains numbers, operators, and Spaces. Stack can be used in the calculation process

  • You can divide all Spaces in string s by s = s.place (/\s+/g,””)

  • Num = num * 10 + Number(s[I]

  • Add stack. Push (num)

  • Subtraction stack. Push (num)

  • Stack. Push (stack.pop() * num)

  • Division stack. Push (stack. Pop ()/num | 0)

  • Assuming s = “3+ 5/2”, define the stack and ‘

  • Remove all Spaces in string s with s = s.place (/\s+/g,””)

  • If num = num * 10 + Number(s[I])

  • If it’s not, it means it’s an operator and you’re trying to figure out what kind of operator it is

  • If it’s addition, it goes to stack.push(num).

  • If it’s subtraction, go to stack.push(-num).

  • Stack. Push (stack.pop() * num)

  • If the division is due to the need to calculate the results stack. Push (stack. Pop ()/num | 0)

  • When the result of the corresponding operator is executed, num must be reassigned to 0

  • Repeat the above operation to add the elements in the stack and return the result

Code implementation

/** * @param {string} s * @return {number} */ var calculate = function (s) { s = s.replace(/\s+/g,""); let stack = new Array() let preSign = "+" let num = 0 let n = s.length for (let i = 0; i < n; i++) { if (! isNaN(Number(s[i]))) { num = num * 10 + Number(s[i]) } if (isNaN(Number(s[i])) || i === n - 1) { switch (preSign) { case  "+": stack.push(num) break case "-": stack.push(-num) break case "*": stack.push(stack.pop() * num) break default: stack.push(stack.pop() / num | 0) break } preSign = s[i] num = 0 } } let ans = 0 while (stack.length) { ans += stack.pop() } return ans };Copy the code