"""
        main idea: each number is constrained by its operator right before it. note first number's operator by default is  +; 
        In addition, there are 4 cases: 1. number 2. operator 3. space 4. end of the loop  
        """
class Solution:
    def calculate(self, s: str) -> int:
        # time O(N) space O(N)
        num = 0
        st = []
        sign = '+'
        for i in range(len(s)):
            c = s[i]
            if c.isdigit():
                num = num *10 + int(c)
            if (not c.isdigit() and c!= ' ') or i == len(s)-1:
                if sign == '+':
                    st.append(num)
                elif sign == '-':
                    st.append(-num)
                elif sign == '*':
                    st[-1] = st[-1]*num
                elif sign == '/' and num!=0:# for case: ' 3/2 '   where last digit is ' '. 
                    st[-1] = int(st[-1]/float(num))
                num = 0
                sign = c
        return sum(st)