Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def calculate(self, s: str) -> int:
- stack = []
- num = 0
- sign = "+" # keep track of the last operator
- for i, ch in enumerate(s):
- if ch.isdigit():
- num = num * 10 + int(ch)
- # if operator or end of string
- if ch in "+-*/" or i == len(s) - 1:
- if sign == "+":
- stack.append(num)
- elif sign == "-":
- stack.append(-num)
- elif sign == "*":
- stack.append(stack.pop() * num)
- elif sign == "/":
- prev = stack.pop()
- # truncate towards zero
- stack.append(int(prev / num))
- sign = ch
- num = 0
- # ignore spaces
- return sum(stack)
Advertisement
Add Comment
Please, Sign In to add comment