class Solution:
def calculate(self, s: str) -> int:
op = '+'
res = prev_num = num = 0
for i,c in enumerate(s):
if c.isdigit():
num = num * 10 + int(c)
if c in '+-*/' or i == len(s) - 1:
if op == '+':
res += prev_num
prev_num = num
if op == '-':
res += prev_num
prev_num = -num
if op == '*':
prev_num *= num
if op == '/':
prev_num = int(prev_num/num)
num = 0
op = c
res+=prev_num
return res
class Solution:
def calculate(self, s: str) -> int:
stack = []
op = '+'
num = 0
for i, c in enumerate(s):
print(f'---------when char is {c}----------------------------------------------')
if c.isdigit():
num = num * 10 + int(c)
print(f'Deal with char, the current number {num}')
if c in "+-/*" or i == len(s) - 1:
# print(f'Deal with op, the current op is {op}, now we are doing:')
if op == '+':
print(f'op is {op}, push {num} into stack')
stack.append(num)
if op == '-':
print(f'op is {op}')
print(f'push - {num} into stack')
stack.append(-num)
if op == '*':
pop = stack.pop()
print(f'op is {op}, pop {pop} from stack,push {num} * {pop} into stack')
stack.append(pop * num)
if op == '/':
print(f'push {num} / {stack.pop()} into stack')
stack.append(stack.pop() // num)
print(f'set {num} to 0, set {op} to {c}')
num = 0
op = c
return sum(stack)
s = Solution()
s.calculate("1+2*3*4")
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
stack = []
op ='+'
snum =''
n = len(s)
res = 0
for ii,i in enumerate(s):
if i.isdigit():
snum += i
if i in "+-*/" or ii == n-1:
if op == '+':
stack.append(int(snum))
elif op == '-':
stack.append(-int(snum))
elif op == '*':
cur = stack.pop()
stack.append(cur*int(snum))
elif op == '/':
cur = stack.pop()/int(snum)
stack.append(math.floor(cur)) if cur >= 0 else stack.append(math.ceil(cur))
snum =''
op = i
for i in stack :
res += i
return res