The 22nd day of my participation in the November Gwen Challenge, the event details: the last Gwen Challenge 2021

Basic Calculator II

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

Integer division preserves only integer parts.

Solution: stack
  1. Store the number on the stack. If encounter+ -Operator:+Put it right on the stack,-Add a negative sign to the number if it hits* /These two operators have a higher priority and need to compute the current number and the number popping out of the top of the stack to get a result, and then put it on the stack again.
  2. And then you add up all the elements on the stack and you get the result of the calculator.
/ * * *@param {string} s
 * @return {number}* /
 var calculate = function(s) {
    // First remove the Spaces on both sides
    s = s.trim();
    var n = s.length; 
    var stack = []
    let preSig = '+'; // Initializes symbolic variables
    let num = 0
    for(let i = 0; i< n; ++i){
        let ch = s[i]
        // if it is a numeric judgment, exclude Spaces
        if(!isNaN(Number(s[i])) && s[i] ! = =' ') {// Count numbers with more than one digit such as 23
            num = num * 10 + s[i].charCodeAt() - '0'.charCodeAt()
        }
        I == n-1; I == n-1
        if(isNaN(Number(s[i])) || i === n-1) {switch(preSig){
                case '+':
                    // The plus digit is pushed directly into the stack
                    stack.push(num)
                    break;
                case The '-':
                    // add a minus sign to the stack
                    stack.push(-num)
                    break;
                case The '*':
                    Note that the order is to operate on the top of the stack with the current number
                    stack.push(stack.pop() * num )
                    break;
                default:
                    // Division is the same as multiplication
                    stack.push(stack.pop() / num  | 0)  / / | binary operator or to prevent the occurrence of decimal calculation
            }
            preSig = s[i];
            num = 0}}let ans = 0
    // iterate through the stack and add up the results
    while(stack.length){
        ans += stack.pop()
    }
    return ans;
};
Copy the code

conclusion

Calculators multiply and divide first, so we need to use the idea of a stack. We need to put the number on the stack first, and take the top element out of the stack when we hit / *. And then you add and subtract.

If you like my article, you can [follow ⭐]+[like 👍]+[comment 📃], your three companies is my motivation, I look forward to growing up with you ~