smj007

basic calculator

Sep 3rd, 2025
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.87 KB | None | 0 0
  1. class Solution:
  2.     def calculate(self, s: str) -> int:
  3.         stack = []
  4.         res = 0
  5.         num = 0
  6.         sign = 1   # current sign (1 means '+', -1 means '-')
  7.        
  8.         for ch in s:
  9.             if ch.isdigit():
  10.                 num = num * 10 + int(ch)
  11.             elif ch in "+-":
  12.                 res += sign * num
  13.                 num = 0
  14.                 sign = 1 if ch == "+" else -1
  15.             elif ch == "(":
  16.                 # push current result and sign
  17.                 stack.append(res)
  18.                 stack.append(sign)
  19.                 res = 0
  20.                 sign = 1
  21.             elif ch == ")":
  22.                 res += sign * num
  23.                 num = 0
  24.                 res *= stack.pop()  # sign before parenthesis
  25.                 res += stack.pop()  # previous result
  26.             # ignore spaces
  27.  
  28.         return res + sign * num
  29.  
Advertisement
Add Comment
Please, Sign In to add comment