Skip to content

Latest commit

 

History

History
43 lines (42 loc) · 1.5 KB

227. Basic Calculator II.md

File metadata and controls

43 lines (42 loc) · 1.5 KB

227. Basic Calculator II (Medium)

[tag] stack

  • use a stack to push numbers and do operations when meet previous operator.
  • use a cur_num and a operator variable to store the current number.
  • consider corner cases for the last element.
class Solution:
    def calculate(self, s: str) -> int:
        num_stack = deque()
        cur_num = 0
        operation = '+'
        ans = 0
        i = 0
        while i < len(s):
            cur_char = s[i]
            if cur_char.isdigit():
                cur_num = cur_num * 10 + int(cur_char)
                # print(cur_num)
            if (cur_char != ' ' and not cur_char.isdigit()) or i == len(s) - 1:
                
                # print(f"{i, operation, cur_num}")
                # this operation is before any cur_num
                if operation == '+':
                    num_stack.append(cur_num)
                if operation == '-':
                    num_stack.append(-cur_num)
                if operation == '*':
                    num1 = num_stack.pop()
                    num_stack.append(num1 * cur_num)
                if operation == '/':
                    num1 = num_stack.pop()
                    num2 = num1 // cur_num
                    if num2 < 0 and num1 % cur_num:
                        num2 += 1
                    num_stack.append(num2)
                operation = cur_char
                cur_num = 0
            i += 1
        # print(num_stack)
        while num_stack:
            ans += num_stack.pop()
        return ans