imashutosh51

basic calculator II

Oct 18th, 2022 (edited)
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.60 KB | None | 0 0
  1. '''
  2. Precedence:
  3. *,/ ->Left to right as per in expression
  4. +,- ->Left to right as per in expression
  5.  
  6. 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.
  7.  
  8. so,* and division should be handles first.
  9. so we will be handling first * and division so after resolving multiplication and division we are only
  10. having positive and negative numbers so we will store positive and negative numbers in stack and finally
  11. we will add all numbers.
  12. '''
  13.  
  14. from typing import List
  15. class Solution:
  16.     def calculate(self, s: str) -> int:
  17.         stack = []
  18.         i = 0
  19.         n = len(s)
  20.         prev_operator = '+'
  21.        
  22.         while i < n:
  23.             if s[i] == ' ':
  24.                 i += 1
  25.                 continue
  26.            
  27.             num = 0
  28.             # extract number
  29.             while i < n and s[i].isdigit():
  30.                 num = num * 10 + int(s[i])
  31.                 i += 1
  32.            
  33.             if prev_operator == '+':
  34.                 stack.append(num)
  35.             elif prev_operator == '-':
  36.                 stack.append(-num)
  37.             elif prev_operator == '*':
  38.                 stack.append(stack.pop() * num)
  39.             elif prev_operator == '/':
  40.                 # important: truncate toward zero like C++
  41.                 stack.append(int(stack.pop() / num))
  42.            
  43.             if i < n:
  44.                 prev_operator = s[i]
  45.                 i += 1
  46.        
  47.         return sum(stack)
Advertisement
Add Comment
Please, Sign In to add comment