【Leetcode】计算器

思路

用栈来完成;

  • 考虑到运算关系,先乘除后加减;
  • 此外,一般计算式首个数字式正数;
  • 判断字符是否为数字,str.isdigit()
  • 字符转数字:ord(str) - ord(‘0’)
  • 遇到加减符,压栈数字;遇到乘除符,先运算再压栈
  • 遍历完后,再将栈内数字求和

代码

class Solution:
    def calculate(self, s: str) -> int:
        stack = []
        n = len(s)
        preSign = '+'
        num = 0
        for i in range(n):
            if s[i] != ' ' and s[i].isdigit():
                num = num * 10 + ord(s[i]) - ord('0')

            if i == n - 1 or s[i] in '+-*/':
                if preSign == '+':
                    stack.append(num)
                elif preSign == '-':
                    stack.append(-num)
                elif preSign == '*':
                    stack.append(stack.pop() * num)
                else:
                    stack.append(stack.pop // num)
                
                preSign = s[i]
                num = 0
        
        return sum(stack)

你可能感兴趣的:(力扣,leetcode,算法,职场和发展)