Topic link

LeetCode: leetcode-cn.com/problems/ba…

Title introduction

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

Integer division preserves only integer parts.

The sample

Input: s = "3+2*2" Output: 7Copy the code
Input: s = "3/2" Output: 1Copy the code
Input: s = "3+ 5/2" Output: 5Copy the code

Implementation approach

1, because the multiplication and division method has a higher priority than addition and subtraction, so the multiplication and division operation is carried out first, and the integer after the operation is put back to the corresponding position of the original expression, and then a series of addition and subtraction can be carried out. 2, in the implementation, the stack data structure can be considered. Saves all integers to be added or subtracted at the end. For the integer that is the addition and subtraction method, the number that is the multiplication and division method can be calculated with the top element of the stack before being pushed onto the stack.

Code implementation

/ * * *@param {string} s
 * @return {number}* /
 var calculate = function(s) {
     s = s.trim(); // Remove whitespace from both sides of the string
     const stack = [];
     let preSign = '+'; // Record symbols. By default, the first digit is preceded by a +, which does not affect the number
     let num = 0; // Record the current number
     const n = s.length;
     for(let i=0; i<n; ++i){// Find all the numbers
         if(!isNaN(Number(s[i])) && s[i] ! = =' '){
             num = num * 10 + s[i].charCodeAt() - '0'.charCodeAt();
         }
             // Find all symbols
         if(isNaN(Number(s[i])) || i === n-1) {switch(preSign){
                 case '+':
                     stack.push(num); // If it is +, add it directly to the stack
                     break;
                 case The '-':
                     stack.push(-num); // If it is -, add -num to stack
                     break;
                 case The '*':
                     stack.push(stack.pop() * num); // If it is *, add the current number to the stack multiplied by the top element, since multiplication and division take precedence
                     break;
                 default:
                     stack.push(parseInt(stack.pop() / num)); // If it is /, the top element/current number is added to the stack and only integers are taken
                     break; } preSign = s[i];// Replace the value of preSign
         num = 0; }}let ans = 0; // Record the calculated result
 while(stack.length){
         // Add all the top elements
     ans += stack.pop();
 }
 return ans;
 }
Copy the code