Likou Brushing Notes: 227. Basic Calculator II (The stack handles the priority of operators, mainly because the logic should be clear, the code is very simple, and the little cousin can understand it)

topic:

227、Basic Calculator II

Give you a string expression s, please implement a basic calculator to calculate and return its value.

Integer division only retains the integer part.

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

prompt:

1 <= s.length <= 3 * 10^5
s is composed of integers and operators ('+','-','*','/'), separated by some spaces,
s represents a valid expression
All integers in the expression are non-negative integers and are in the range [0, 2^31-1]. The
question data guarantees that the answer is a 32-bit integer

Problem solution ideas:

Since multiplication and division take precedence over addition and subtraction calculations, you may wish to consider performing all multiplication and division operations first, and put the integer value after these multiplication and division operations back to the corresponding position of the original expression, then the value of the entire expression is equal to a series of integer addition and subtraction After the value.

Based on this, we can use a stack to store the value of these integers (after multiplication and division operations). For the number after the plus and minus sign, push it directly into the stack; for the number after the multiplication and division sign, you can directly calculate with the top element of the stack, and replace the top element of the stack with the result of the calculation.

Specifically, traverse the string s, and use the variable preSign to record the operator before each number. For the first number, the operator before it is regarded as a plus sign. Every time it traverses to the end of the number, the calculation method is determined according to preSign:

Plus sign: push the number onto the stack;
minus sign: push the opposite number of the number onto the stack;
multiply and divide sign: calculate the number and the top element of the stack, and replace the top element of the stack with the calculation result.
In the code implementation, if an operator is read, or the end of the string is traversed, it is considered that the end of the number has been traversed. After processing the number, update preSign to the character currently traversed.

After traversing the string s, accumulate the elements in the stack, which is the value of the string expression.

Problem solution python code:

class Solution:
    def calculate(self, s: str) -> int:
        stack = []
        num, preSign = 0, ""   # preSign为当前运算符的上一个符号
        for i in range(len(s)):
            if s[i].isdigit():
                num = num*10+int(s[i])
            if not s[i].isdigit() and s[i]!=" " or i==len(s)-1:  # 在下一个符号或字符结束处进行计算
                if preSign=="":
                    stack.append(num)
                elif preSign=="+" or preSign=="-":
                    stack.append(num if preSign=="+" else -num)
                elif preSign=="*":
                    stack[-1] *= num
                elif preSign=="/":
                    stack[-1] /= num
                    stack[-1] = int(stack[-1])   # 取整
                num = 0
                preSign = s[i]
            # print(s[i], preSign, stack)
        return sum(stack)

Author: a-qing-ge
links: https://leetcode-cn.com/problems/basic-calculator-ii/solution/guan-fang-ti-jie-zhan-pythonban-by-a-qin-p00z/
sources : LeetCode https://leetcode-cn.com/problems/basic-calculator-ii/

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/114653105