Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Precedence:
- *,/ ->Left to right as per in expression
- +,- ->Left to right as per in expression
- Note: Division and Multiplication have the same precedence but while traveling from left to right, if division comes first, it has higher precendence in the expression and same for the multiplication also so order from left to right also matters.
- so,* and division should be handles first.
- so we will be handling first * and division so after resolving multiplication and division we are only
- having positive and negative numbers so we will store positive and negative numbers in stack and finally
- we will add all numbers.
- '''
- from typing import List
- class Solution:
- def calculate(self, s: str) -> int:
- stack = []
- i = 0
- n = len(s)
- prev_operator = '+'
- while i < n:
- if s[i] == ' ':
- i += 1
- continue
- num = 0
- # extract number
- while i < n and s[i].isdigit():
- num = num * 10 + int(s[i])
- i += 1
- if prev_operator == '+':
- stack.append(num)
- elif prev_operator == '-':
- stack.append(-num)
- elif prev_operator == '*':
- stack.append(stack.pop() * num)
- elif prev_operator == '/':
- # important: truncate toward zero like C++
- stack.append(int(stack.pop() / num))
- if i < n:
- prev_operator = s[i]
- i += 1
- return sum(stack)
Advertisement
Add Comment
Please, Sign In to add comment