Skip to content

Latest commit

 

History

History
47 lines (46 loc) · 1.27 KB

224. Basic Calculator.md

File metadata and controls

47 lines (46 loc) · 1.27 KB

224. Basic Calculator (Hard)

[tag] stack, calculator

  • Tips:
    • Using while loop inside for loop dont forgot to i -= 1
    • for python, i cannot be changed in for i in range(10)
  • use sum and sign to store the current sum and previous sign
  • use while loop to go though all digit of a number.
  • when '(' append, when ')' pop.
'''
cur_num 1
sign 1
"(1+(4+5+2)-3)+(6+8)"
     ^
sum = 
stack: 1 + 
stack: 23   
'''
class Solution:
    def calculate(self, s: str) -> int:
        cur_sum = 0
        sign = 1
        num_stack = deque()
        i = 0
        while i < len(s):
            if s[i].isdigit():
                cur_num = 0
                while i < len(s) and s[i].isdigit():
                    cur_num = cur_num * 10 + int(s[i])
                    i += 1
                cur_sum += cur_num * sign
            else:
                if s[i] == '(':
                    num_stack.append(cur_sum)
                    num_stack.append(sign)
                    cur_sum = 0
                    sign = 1
                if s[i] == '+':
                    sign = 1
                if s[i] == '-':
                    sign = -1
                if s[i] == ')':
                    cur_sum = cur_sum * num_stack.pop() + num_stack.pop() 
                i += 1
        return cur_sum