Skip to content

Commit

Permalink
re-solve "224. Basic Calculator"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Oct 26, 2024
1 parent 7c00bd1 commit 6d5259d
Showing 1 changed file with 21 additions and 18 deletions.
39 changes: 21 additions & 18 deletions src/basic_calculator.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,33 @@
SIGN = {
"+": +1,
"-": -1,
}


class Solution:
def calculate(self, s: str) -> int:
num, sign, stack = 0, 1, [0]
current, sign, stack = 0, +1, [0]

for x in s:
if x.isnumeric():
num = num * 10 + int(x)
if x.isdigit():
current = current * 10 + int(x)
elif x == " ":
continue
elif x == "+":
stack[-1] += num * sign
sign = 1
num = 0
elif x == "-":
stack[-1] += num * sign
sign = -1
num = 0
pass
elif x in SIGN:
stack[-1] += current * sign
sign = SIGN[x]
current = 0
elif x == "(":
stack.extend([sign, 0])
stack.append(sign)
stack.append(0)
sign = 1
num = 0
current = 0
elif x == ")":
last = (stack.pop() + num * sign) * stack.pop()
last = (stack.pop() + current * sign) * stack.pop()
stack[-1] += last
sign = 1
num = 0
current = 0
else:
raise ValueError("unknown token: {x}")
raise ValueError(f"unknown token: {x}")

return stack[-1] + num * sign
return stack[-1] + current * sign

0 comments on commit 6d5259d

Please sign in to comment.