-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path227.基本计算器-ii.py
34 lines (32 loc) · 911 Bytes
/
227.基本计算器-ii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#
# @lc app=leetcode.cn id=227 lang=python3
#
# [227] 基本计算器 II
#
# @lc code=start
class Solution:
def calculate(self, s: str) -> int:
s = s.replace(" ","")
n = len(s)
stack = []
preSign = '+'
num = 0
for i in range(n):
if s[i].isdigit():
num = num * 10 + ord(s[i]) - ord('0')
if i == n - 1 or s[i] in '+-*/':
if preSign == '+':
stack.append(num)
elif preSign == '-':
stack.append(-num)
elif preSign == '*':
stack.append(stack.pop() * num)
else:
stack.append(int(stack.pop() / num))
preSign = s[i]
num = 0
return sum(stack)
# return eval(s.replace('/','//'))
# @lc code=end
S = Solution()
print(S.calculate(" 3/2 "))