smj007

basic calculator II

Sep 3rd, 2025
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  1. class Solution:
  2.     def calculate(self, s: str) -> int:
  3.         stack = []
  4.         num = 0
  5.         sign = "+"   # keep track of the last operator
  6.  
  7.         for i, ch in enumerate(s):
  8.             if ch.isdigit():
  9.                 num = num * 10 + int(ch)
  10.  
  11.             # if operator or end of string
  12.             if ch in "+-*/" or i == len(s) - 1:
  13.                 if sign == "+":
  14.                     stack.append(num)
  15.                 elif sign == "-":
  16.                     stack.append(-num)
  17.                 elif sign == "*":
  18.                     stack.append(stack.pop() * num)
  19.                 elif sign == "/":
  20.                     prev = stack.pop()
  21.                     # truncate towards zero
  22.                     stack.append(int(prev / num))
  23.  
  24.                 sign = ch
  25.                 num = 0
  26.  
  27.             # ignore spaces
  28.  
  29.         return sum(stack)
  30.  
Advertisement
Add Comment
Please, Sign In to add comment